Accessing a static property of a child in a parent method

前端 未结 9 1241
孤城傲影
孤城傲影 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:49

    Yes, override DoSomething:

    class Child
    {
        static new string MyField = "ChildField";
    
        public virtual string DoSomething()
        {
            return MyField;
        }
    
    }
    
    0 讨论(0)
  • 2021-01-21 06:53

    Use a static property instead of a static variable. Then you can override the property in the child class instead of creating a "new" field.

    0 讨论(0)
  • 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.

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