2013-05-18 47 views
0

在C#中,当通用列表包含派生类时,是最佳访问基类属性的方法。使用通用列表从派生类访问基类的属性

public BaseClass1 
{ 
    public Property A{get;set;} 
    public Property B{get;set;} 
} 
public BaseClass2:BaseClass1 
{ 
    public Property C{get;set;} 
    public Property D{get;set;} 
} 
public classA:BaseClass2 
{ 
} 

public class Implement 
    { 
    List<classA> list1 = new List<classA>() 

    Console.WriteLine("Would you like to add another person");//If yes I would like add person to the list dynamically 

    { 
     //Is it possible to acesses properties of Baseclass using derived class List 
     List1.Property A = Console.readline();//read input from console 
     List1.Property B = Console.readline();//read input from console 
      . 
      . 
     List.Property D = Console.readline();//read input from console 

     List1.add(Property A,Property B);//add properties of baseclass1 and baseclass2 as well as derived class 

    } 
    } 

我想借此从控制台基类属性的值,并将这些值添加到列表中,如果用户想增加CLASSA的多个对象增加了名单。 这可能吗?

+0

您可以访问基类的属性,但是您必须构造一个类型为“classA”的新对象,并将其添加到列表中。该列表不会奇迹般地获取它所包含类型的所有属性。 –

回答

1
List1.Add(new ClassA { A = a, B = b, C = c }); 
相关问题