有什么区别
public void MyMethod<T>(IList<T> myParameter) where T : IMyInterface
和
public void MyMethod(IList<IMyInterface> myParameter)
?
最佳答案
IList<T>
不是 covariant , 所以你不能传递 IList<SomeObjectThatImplementsIMyInterface>
到第二种方法。
假设你可以,并且你有:
class MyClass1 : IMyInterface {}
class MyClass2 : IMyInterface {}
和MyMethod
的实现是:
MyMethod(IList<IMyInterface> myParameter)
{
// perfectly valid since myParameter can hold
// any type that implements IMyInterface
myParameter.Add(new MyClass2());
}
如果你想打电话
MyMethod(new List<MyClass1>()) ;
它会在运行时失败,因为列表被定义为包含 MyClass1
对象,不能容纳 MyClass2
对象。
关于c# - "A <T>(IList<T> x) where T : I"和 "A(IList<I> x)"之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28100405/