Accessing a static property of a child in a parent method

前端 未结 9 1316
孤城傲影
孤城傲影 2021-01-21 06:07

Say I have the following code:

class Parent
{

    static string MyField = \"ParentField\";

    public virtual string DoSomething()
    {
        return MyField         


        
9条回答
  •  孤独总比滥情好
    2021-01-21 06:54

    The only way is overriding DoSomething method or else it is not possible. The DoSomething in Parent method essentially translates to:

    public virtual string DoSomething()
        {
            return Parent.MyField;
        }
    

    When you "new" a property, it only applies to that type - in this case Child class. If the property is accessed via the 'Parent', it will always return the original property.

提交回复
热议问题