【问题标题】:Difference between "A <T>(IList<T> x) where T : I" and "A(IList<I> x)"?“A <T>(IList<T> x) where T : I”和“A(IList<I> x)”之间的区别?
【发布时间】:2015-03-21 22:21:13
【问题描述】:

有什么区别

public void MyMethod<T>(IList<T> myParameter) where T : IMyInterface

public void MyMethod(IList<IMyInterface> myParameter)

?

【问题讨论】:

  • 一个是通用的,另一个不是 :) 但这显然不是您要问的 - 您能否评论/接受 D Stanley 的回答,以便清楚您在寻找什么。

标签: c# generics methods types interface


【解决方案1】:

IList&lt;T&gt; 不是covariant,因此您不能将IList&lt;SomeObjectThatImplementsIMyInterface&gt; 传递给第二种方法。

假设你可以,并且你有:

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 对象。

【讨论】:

  • 优秀的答案。措辞和布局都很好。
猜你喜欢
  • 1970-01-01
  • 2011-09-01
  • 2012-10-02
  • 2017-06-10
  • 2012-05-28
  • 1970-01-01
  • 2019-06-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多