我在使用泛型時如何理解多態性是如何工作的問題。作爲一個例子,我已經定義了以下程序:請幫我理解在c#中使用泛型時的多態性問題#
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 2010-08-25 12:27:08
@Greg:從好的方面來說,我覺得自己對這些概念的理解最近已經真正充實了,因爲這樣的問題已經出現過多! – 2010-08-25 12:28:20
這個概念很好,但名字很可怕。 :) – Greg 2010-08-25 12:59:01