【发布时间】:2010-04-24 19:38:13
【问题描述】:
有没有一种方法可以覆盖扩展方法(提供更好的实现),而无需显式地强制转换为它们?我正在实现一种能够比默认扩展方法更有效地处理某些操作的数据类型,但我想保持 IEnumerable 的通用性。这样任何 IEnumerable 都可以传递,但是当我的类传入时,它应该更高效。
作为一个玩具示例,请考虑以下内容:
// 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,而不是改变扩展方法。
标签: c# .net linq mono extension-methods