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

前端 未结 7 638
夕颜
夕颜 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:30

    If you are doing this a lot, another option would be to create an extension method on the list to give you back the correctly typed enumeration. i.e.

      public static class MyBaseListExtensions
      {
        public static IEnumerable GetAllAs(this List list)
        {
          foreach (var obj in list)
          {
            if (obj is ClassA)
            {
              yield return (ClassA)obj;
            }
          }
        }
    
        public static IEnumerable GetAllbs(this List list)
        {
          foreach (var obj in list)
          {
            if (obj is ClassB)
            {
              yield return (ClassB)obj;
            }
          }
        }
      }
    

    Then you could use it like....

    private void button1_Click(object sender, EventArgs e)
    {
      ClassA a1 = new ClassA() { PropertyA = "Tim" };
      ClassA a2 = new ClassA() { PropertyA = "Pip" };
      ClassB b1 = new ClassB() { PropertyB = "Alex" };
      ClassB b2 = new ClassB() { PropertyB = "Rachel" };
    
      List list = new List();
      list.Add(a1);
      list.Add(a2);
      list.Add(b1);
      list.Add(b2);
    
      foreach (var a in list.GetAllAs())
      {
        listBox1.Items.Add(a.PropertyA);
      }
    
      foreach (var b in list.GetAllbs())
      {
        listBox2.Items.Add(b.PropertyB);
      }
    }
    

提交回复
热议问题