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

前端 未结 7 618
夕颜
夕颜 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:34

    Further to TimJ's answer, you can write one extension method that will work for all types:

    public static IEnumerable<T> OfType<T>(this IEnumerable list)
    {
        foreach (var obj in list)
        {
            if (obj is T)
                yield return (T)obj;
        }
    }
    

    Or if you have Linq, that function is in the namespace System.Linq.

    0 讨论(0)
提交回复
热议问题