【发布时间】:2010-08-25 12:04:37
【问题描述】:
在使用泛型时,我无法理解多态性的工作原理。例如,我定义了以下程序:
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;
所以,至少我没有完全误解这一点。我不确定如何编写一个接受符合相同接口的通用类集合的方法。
如果需要的话,我有一个彻底解决这个问题的计划,但我真的更愿意做正确的事情。
提前谢谢你。
【问题讨论】:
-
这是人们大谈特谈协变和逆变等可怕词的地方。
-
@Greg:从好的方面来说,我觉得我对这些概念的自己的理解最近确实得到了充实,因为这样的问题太多了起来!
-
概念很好,但名字很吓人。 :)
-
@Greg:同意。我建议我们将它们更改为gobbling and spewing。
标签: c# asp.net generics asp.net-mvc-2 nested-generics