차이점은 무엇입니까
public void MyMethod<T>(IList<T> myParameter) where T : IMyInterface
과
public void MyMethod(IList<IMyInterface> myParameter)
?
IList<T>
공변 이 아니므로 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
합니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다