数组或链表如何包含不同的对象作为元素?如何在C#或C ++中实现?
答案 0 :(得分:3)
数组可以包含不同类对象的唯一方法是它们都有一个公共库,并且声明该数组包含该公共库。例如,你可以有3个这样的类:
class MyBase {
public int SomeParameter { get; set; }
}
class MyFirstChild : MyBase {
public int SomeOtherParameter { get; set; }
}
class MySecondChild : MyBase {
public int SomeOtherParameter { get; set; }
}
你的数组将被声明为:
MyBase[] myArray = new MyBase[3];
现在您可以将MyBase
或其子类型的不同对象放入此数组中,如下所示:
myArray[0] = new MyBase();
myArray[1] = new MyFirstChild();
myArray[2] = new MySecondChild();
如果所有这些都实现某个界面而不是从MyBase
继承,那么同样可行。
答案 1 :(得分:3)
使用c#你可以声明一个接口,两种类型都实现了接口:
public interface IType
{}
public class Thing : IType
{}
public class Thing2 : IType
{}
List<IType> list = new List<IType>();
list.Add(new Thing1());
list.Add(new Thing2());
答案 2 :(得分:1)
在C ++中,它不能。但是,它可以包含:
variant
(静态指定的类型集合的联合)和any
(用于保存任何类型的多态包装)。我对C#一无所知,但我想你可以做类似的事情。
答案 3 :(得分:0)
使用void指针数组
像void * ptr [];
这样的东西