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

前端 未结 7 658
夕颜
夕颜 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

    Certainly you can downcast, like so:

    for (int i = 0; i < MyList.Count; i++)
    {
        if (MyList[i] is ClassA)
        {
            var a = ((ClassA)MyList[i]).PropertyA;
            // do stuff with a
        }
    
        if (MyList[i] is ClassB)
        {
            var b = ((ClassB)MyList[i]).PropertyB;
            // do stuff with b
        }
    }
    

    ... However, you should take another look at what you're trying to accomplish. If you have common code that needs to get to properties of ClassA and ClassB, then you may be better off wrapping access to those properties up into a shared, virtual property or method in the ancestor class.

    Something like:

    public class BaseClass
    {
        public virtual void DoStuff() { }
    }
    
    public class ClassA : BaseClass
    {
        public object PropertyA { get; set; }
    
        public override void DoStuff() 
        {
            // do stuff with PropertyA 
        }
    }
    
    public class ClassB : BaseClass
    {
        public object PropertyB { get; set; }
    
        public override void DoStuff() 
        {
            // do stuff with PropertyB
        }
    }
    

提交回复
热议问题