有沒有一種方法可以覆蓋擴展方法(提供更好的實現),而不必明確地轉換給它們?我正在實現一種數據類型,它能夠比默認的擴展方法更有效地處理某些操作,但我想保持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