有没有一种方法可以覆盖扩展方法(提供更好的实现),而不必明确地转换给它们?我正在实现一种数据类型,它能够比默认的扩展方法更有效地处理某些操作,但我想保持IEnumerable的通用性。这样任何IEnumerable都可以传递,但是当我的类传入时,它应该更有效率。重写LINQ扩展方法
当作玩具例子,考虑以下因素:
// Compile: dmcs -out:test.exe test.cs
using System;
namespace Test {
public interface IBoat {
void Float();
}
public class NiceBoat : IBoat {
public void Float() {
Console.WriteLine ("NiceBoat floating!");
}
}
public class NicerBoat : IBoat {
public void Float() {
Console.WriteLine ("NicerBoat floating!");
}
public void BlowHorn() {
Console.WriteLine ("NicerBoat: TOOOOOT!");
}
}
public static class BoatExtensions {
public static void BlowHorn (this IBoat boat) {
Console.WriteLine ("Patched on horn for {0}: TWEET", boat.GetType().Name);
}
}
public class TestApp {
static void Main (string [] args) {
IBoat niceboat = new NiceBoat();
IBoat nicerboat = new NicerBoat();
Console.WriteLine ("## Both should float:");
niceboat.Float();
nicerboat.Float();
// Output:
// NiceBoat floating!
// NicerBoat floating!
Console.WriteLine();
Console.WriteLine ("## One has an awesome horn:");
niceboat.BlowHorn();
nicerboat.BlowHorn();
// Output:
// Patched on horn for NiceBoat: TWEET
// Patched on horn for NicerBoat: TWEET
Console.WriteLine();
Console.WriteLine ("## That didn't work, but it does when we cast:");
(niceboat as NiceBoat).BlowHorn();
(nicerboat as NicerBoat).BlowHorn();
// Output:
// Patched on horn for NiceBoat: TWEET
// NicerBoat: TOOOOOT!
Console.WriteLine();
Console.WriteLine ("## Problem is: I don't always know the type of the objects.");
Console.WriteLine ("## How can I make it use the class objects when the are");
Console.WriteLine ("## implemented and extension methods when they are not,");
Console.WriteLine ("## without having to explicitely cast?");
}
}
}
是否有一种方式来获得从第二种情况下的行为,而无需显式铸造?这个问题可以避免吗?
我认为你应该在你的类中实现IEnumerable更高效,而不是改变扩展方法。 – 2010-04-24 19:43:06