使用泛型列表从派生类访问基类的属性

本文关键字:访问 基类 属性 派生 泛型 列表 | 更新日期: 2023-09-27 18:14:09

在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 
    }
   }

我想从控制台获取基类属性的值,并将这些值添加到列表中,如果用户想添加更多的类a对象,则增加列表。这可能吗?

使用泛型列表从派生类访问基类的属性

List1.Add( new ClassA { A = a, B = b, C = c } );