Accessing a property of derived class from the base class in C#

前端 未结 7 659
夕颜
夕颜 2020-12-03 06:06

In C#, what is the best way to access a property of the derived class when the generic list contains just the base class.

public class ClassA : BaseClass
{
          


        
7条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-03 06:25

    You would need to have the properties be declared as virtual on the base class and then override them in the derived class.

    Ex:

    public class ClassA : BaseClass
    {
       public override object PropertyA { get; set; }
    }
    
    public class ClassB: BaseClass
    {
        public override object PropertyB { get; set; }
    }
    
    public class BaseClass
    {
        public virtual object PropertyA { get; set; }
        public virtual object PropertyB { get; set; }
    }
    
    public void Main
    {
        List MyList = new List();
        ClassA a = new ClassA();
        ClassB b = new ClassB();
    
        MyList.Add(a);
        MyList.Add(b);
    
        for(int i = 0; i < MyList.Count; i++)
        {
         // Do something here with the Property
            MyList[i].PropertyA;
            MyList[i].PropertyB;      
        }
    }
    

    You would either need to implement the property in the base class to return a default value (such as null) or to make it abstract and force all the derived classes to implement both properties.

    You should also note that you could return different things for say PropertyA by overrideing it in both derived classes and returning different values.

提交回复
热议问题