"A <T>(IList <T> x),其中T:I"和"A(IList <I> x)"之间的区别?

Eas*_*one 1 c# generics methods types interface

有什么区别

public void MyMethod<T>(IList<T> myParameter) where T : IMyInterface
Run Code Online (Sandbox Code Playgroud)

public void MyMethod(IList<IMyInterface> myParameter)
Run Code Online (Sandbox Code Playgroud)

D S*_*ley 8

IList<T>不是协变的,所以你无法传递IList<SomeObjectThatImplementsIMyInterface>给第二种方法.

假设你可以,而且你有:

class MyClass1 : IMyInterface {}
class MyClass2 : IMyInterface {}
Run Code Online (Sandbox Code Playgroud)

并执行MyMethod是:

MyMethod(IList<IMyInterface> myParameter)
{
    // perfectly valid since myParameter can hold 
    // any type that implements IMyInterface
    myParameter.Add(new MyClass2());
}
Run Code Online (Sandbox Code Playgroud)

如果你试着打电话

MyMethod(new List<MyClass1>()) ;
Run Code Online (Sandbox Code Playgroud)

它会在运行时失败,因为列表被定义为包含MyClass1对象而不能保存MyClass2对象.