다음 코드 고려 C#에서 공통 인터페이스를 구현할 때 구현하는 인터페이스로 일반적인 캐스팅하는 방법 : 당신이 얻을모두에서 유형 매개 변수가
var abstractContainer = (IContainer<Thing>) concreteContainer;
:이 라인에
public class Thing : IThing { }
public interface IThing {}
public interface IContainer<out T> where T : IThing { }
// This works
// public class Container<T> : IContainer<T> where T : IThing { }
// This doesn't work
public class Container<T> : IContainer<IThing> where T : IThing {}
internal class Program
{
private static void Main(string[] args)
{
var concreteContainer = new Container<Thing>();
var abstractContainer = (IContainer<Thing>) concreteContainer;
}
}
을 다음 런타임 오류 : InvalidCastException: Unable to cast object of type 'CastTest.Container`1[CastTest.Thing]' to type CastTest.IContainer`1[CastTest.Thing]'.
또한 Resharper가있는 경우 Suspecious cast: there is no type in the solution which is inherited from both 'Container<Thing>' and 'IContainer<Thing>'
으로 불만을 제기합니다.
둘 모두에서 상속하는 유형이 필요한 이유는 무엇입니까? Container<T>
은 IContainer<IThing>
을 구현하지 않습니까? Thing
은 IThing
을 구현하고 Container<T>
에 T
을 구현하면 IThing
을 구현할 수 있으므로이 캐스트를 수행 할 수 있어야합니다.
'컨테이너'는'IContainer '이 아닌'IContainer '을 구현합니다. –
Lee
@hvd 뭐, 이제 너 내가 실제로주의를 기울이기를 바라는거야?! Jeez, 사람들은 많이 묻습니다. 와! –