Accessing a static property of a child in a parent method

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

    I don't get why you think you need both "static" and "non-static" environments to call different properties/functions that return the same thing. If you just do this:

    class Parent
    {
        public virtual string DoSomething()
        {
            return "ParentField";
        }
    }
    
    class Child
    {
        public override string DoSomething()
        {
             return "ChildField";
        }
    }
    

    Then this will work like you want:

    Child c = new Child();
    Console.WriteLine(c.DoSomething());
    

    And instead of writing this:

    Console.WriteLine(Parent.MyField);
    Console.WriteLine(Child.MyField);
    

    you just write this:

    Console.WriteLine(new Parent().DoSomething());
    Console.WriteLine(new Child().DoSomething());
    

    Is there some other constraint on the problem that makes this unacceptable? Is creating new objects of these classes extremely expensive for some reason, for example?

提交回复
热议问题