c# - "A <T>(IList<T> x) where T : I"和 "A(IList<I> x)"之间的区别?

标签 c# generics methods types interface

有什么区别

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/

相关文章:

c# - C# smtp.gmail.com 和端口号 587 中目标主机拒绝发送电子邮件

javascript,如何从 XML 获取值

c# - 是否可以创建仅接受具有特定属性的类型的泛型类

c# - 文件索引大小大于原始大小

c# - 两台服务器之间的高效文件读/写

c# - 是否应该使用自引用通用继承,如 Customer : Entity<Customer>

java - 泛型和转换为正确的类型

java - Java 是 "pass-by-reference"还是 "pass-by-value"?

c# - 单元测试私有(private)代码

java - Jersey Rest Service 中的多个 PUT 方法