我在理解使用泛型时多态性如何工作时遇到问题。例如,我定义了以下程序:
public interface IMyInterface
{
void MyMethod();
}
public class MyClass : IMyInterface
{
public void MyMethod()
{
}
}
public class MyContainer<T> where T : IMyInterface
{
public IList<T> Contents;
}
然后我可以这样做,效果很好:
MyContainer<MyClass> container = new MyContainer<MyClass>();
container.Contents.Add(new MyClass());
我有许多实现 MyInterface 的类。我想写一个可以接受所有 MyContainer 对象的方法:
public void CallAllMethodsInContainer(MyContainer<IMyInterface> container)
{
foreach (IMyInterface myClass in container.Contents)
{
myClass.MyMethod();
}
}
现在,我想调用这个方法。
MyContainer<MyClass> container = new MyContainer<MyClass>();
container.Contents.Add(new MyClass());
this.CallAllMethodsInContainer(container);
那没有用。当然,因为 MyClass 实现了 IMyInterface,我应该可以直接转换它吗?
MyContainer<IMyInterface> newContainer = (MyContainer<IMyInterface>)container;
那也没有用。我绝对可以将普通的 MyClass 转换为 IMyInterface:
MyClass newClass = new MyClass();
IMyInterface myInterface = (IMyInterface)newClass;
所以,至少我没有完全误解这一点。我不确定如何编写一个接受符合相同接口的通用类集合的方法。
如果需要,我有一个完全解决这个问题的计划,但我真的更愿意正确地完成它。
先感谢您。