且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#从基类访问派生类的属性

更新时间:2023-02-15 15:37:05

当然你可以垂头丧气,像这样:

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

... 但是,您应该再看看您要实现的目标.如果您有需要访问 ClassA 和 ClassB 属性的公共代码,那么***将这些属性的访问权限封装到祖先类中的共享、虚拟属性或方法中.

... 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.

类似于:

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