我已经拿了一份清单。列表的类型是Base类。现在使用继承和多态的帮助我通过使用向上转换将子类添加到列表中。当我在运行时访问列表的元素时,我需要在运行时向下转换它以访问特定的功能,如方法或属性孩子。
class BaseClass
{
public string Id;
}
class childOne : BaseClass
{
public string Name;
}
class childTwo : BaseClass
{
public string Name;
}
class Test {
public List<BaseClass> mylist = new List<BaseClass>();
public void AddMembers()
{
childOne child1 = new childOne();
childTwo child2 = new childTwo();
mylist.Add(child1);
mylist.Add(child2);
}
public void GetChild()
{
Random random = new Random();
int num = random.Next(0, mylist.Count - 1);
var child = mylist[num];
//Find out the type of child ie. ChildOne or childTwo
//At runtime and down cast it two child
//Like childOne ch1 = (childOne)child;
//To use the property of child one or two .
}
}
答案 0 :(得分:0)
它可能对你有帮助
LastNotify Column1 Column2 Column3
1 1 0 0
2 0 1 0
3 0 0 1
4 0 0 0