我是 C# 方面的新手.... (.net 3.5)
我想要一个字典来容纳两种不同类型的对象,其中一种类型是通用的。在遍历列表时,我将调用添加和克隆等方法。 我已经用基类和子类尝试过它....
namespace ConsoleApplication1 {
class Element{
}
class Child1 : Element {
public Child1 Clone() { return clone; }
}
class Child2<T> : Element {
public Child2<T> Clone() { return clone; }
}
class Program {
static void Main(string[] args) {
Dictionary<string, Element> d = new Dictionary<string, Element>();
d.Add("c1", new Child1());
d.Add("c2s", new Child2<string>());
d.Add("c2i", new Child2<int>());
foreach (KeyValuePair<string, Element> kvp in d) {
Element e = kvp.Value.Clone();
}
}
}
}
是否有满足我需求的方法或解决方案?
谢谢! 安娜
最佳答案
您可以在基本类型(Element
)上制作Clone
abstract
或virtual
,并且override
它在派生类型中,但在覆盖时不能更改返回类型,因此它必须是 Element
(没有更具体的)。您可以重新声明方法(new
...),但这会变得困惑,并且您不能override
和new
具有相同类型的相同名称/签名的方法。
但是如果您对返回类型为 Element
感到高兴...
abstract class Element{
public abstract Element Clone();
}
class Child1 : Element {
public override Element Clone() { return /* your code */; }
}
class Child2<T> : Element {
public override Element Clone() { return /* your code */; }
}
关于c# - 列出不同类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2301795/