我时常试图折磨 C# 编译器。今天我想到了这个:
static void CallFirst<T>(T a) where T : IEnumerable<T>
{
a.First().ToString();
}
这是一个简单的错误,因为我想创建以集合为参数的泛型方法,当然应该如下所示:
static void CallFirst2<T>(IEnumerable<T> a)
{
a.First().ToString();
}
无论如何,是否可以调用 CallFirst()
方法?每次通过集合,都期望集合的集合。
如果不是,是不是应该认为是编译时错误?
最佳答案
当然:
class Test : IEnumerable<Test>
{
IEnumerator<Test> IEnumerable<Test>.GetEnumerator()
{
throw new NotImplementedException();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
...
var test = new Test();
CallFirst(test);
关于c# - 其中 T : IEnumerable<T> method constraint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26973337/