Accessing a static property of a child in a parent method

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

    First, let me say that you really should just make MyField virtual and accept that you need to spawn an instance to get it. However, another way of "solving" the problem would be:

    class Parent
    {
        public static string MyField = "ParentField";
        protected virtual MyLocalField = MyField;
    
        public virtual string DoSomething()
        {
            return MyLocalField;
        }
    }
    class Child : Parent
    {
        public static new string MyField = "ChildField";
        protected override MyLocalField = MyField;
    }
    

提交回复
热议问题