【发布时间】:2014-06-10 09:14:31
【问题描述】:
我创建了以下类:
class GenericTest
{
public T Do<T>( T test ) where T : class
{
return test;
}
public IEnumerable<T> Do<T>( List<T> test ) where T : class
{
return test;
}
public IEnumerable<T> Do<T>( IEnumerable<T> test ) where T : class
{
return test;
}
}
这具有 Do() 函数的三个重载。我试图了解方法参数匹配如何在 C# 中为泛型工作,尤其是在接口参数周围。所以,我有以下测试程序:
static void Main( string[] args )
{
GenericTest testing = new GenericTest();
string s = "TEST";
List<string> list = new List<string> {s};
Stack<string> stack = new Stack<string>();
stack.Push( s );
testing.Do( s ); //calls public T Do<T>( T test )
testing.Do( list ); //calls IEnumerable<T> Do<T>( List<T> test )
testing.Do( stack ); //calls public T Do<T>( T test ) where T : class
}
对 Do() 的第一次调用按我的预期工作,然后具体类 List 参数与 List 参数方法很好地匹配,但是当我传递 IEnumerable 时,编译器不使用 IEnumerable 参数方法,而是选择通用 T 方法。这是预期的行为吗?我不能只用泛型中的接口参数重载吗?
【问题讨论】:
-
Eric lippert 有一篇很棒的帖子解释了您的问题:blogs.msdn.com/b/ericlippert/archive/2009/12/10/…
-
这是一个很接近的副本,但这个问题要清楚得多。
-
@HenkHolterman 所以关闭这个问题作为这个问题的副本。它接受的答案是仅链接的答案,因此无论如何都没用
-
但是,这个最多只能得到相同的链接答案。
标签: c# generics interface parameters