我阅读了这个问题,并尝试做类似的事情:
static class ExtentionMethods
{
static public void MyReset<T>(this T col)
{
Console.WriteLine("Not a collection!");
}
static public void MyReset<T, U>(this T col) where T : ICollection<U>
{
col.Clear();
Console.WriteLine("Cleared!");
}
// and maybe more overload for T : IWhatevetInterface<U>
}
这样,实现了ICollection<T>
的List<T>
和其他类会选择第二个方法,而没有实现ICollection
接口的类(比如MyClass
)则会选择第一个方法,例如:
List<int> list1 = new List<int>();
list1.MyReset<List<int>, int>(); // "Cleared!"
MyClass x = new MyClass();
x.MyReset(); // "Not a collection!"
它的功能很好,但问题是,我如何避免为
list1.MyReset<List<int>, int>()
编写<List<int>, int>
?我想简单地写list1.MyReset()
。目标是保持区分
ICollection<T>
和其他类的能力,但也不明确提供泛型参数。回应评论:我计划添加更多重载,因此情况不仅限于
Yes-Collection
和Not-Collection
。
T : IResetable
,T: IWhateverYouLike
等等; 因此,我需要让它们匹配到精确的重载。 - Marson Mao