继承初始化的字段

Pau*_*aul 1 c# inheritance

我真的不了解C#中的一种行为:

class Animal {
        public string species = "animal";

        public void Introduce() {
            Console.WriteLine(species);
        }
    }


    class Cat: Animal {
        new public string species = "cat";

        // public void Introduce() {Console.WriteLine(species);}
    }

    class Program
    {
        static void Main(string[] args)
        {
            var cat = new Cat();
            cat.Introduce();
        }
    }
Run Code Online (Sandbox Code Playgroud)

这段代码在执行时输出>>> animal
对我而言,由于Cat继承了Animal,因此调用cat.Introduce应该在“ cat实例的范围内”调用Animal.Introduce。我不明白为什么该程序选择species动物领域而不是猫领域...

我知道我可以使用变通办法,但是我相信我缺少有关c#设计的一些知识,有人可以解释这种现象吗?

谢谢

Cod*_*ter 10

我不明白为什么该程序选择动物的物种领域而不是猫的物种领域...

因为new修饰符隐藏了继承的species成员...,但仅在Cat实例内部。您在基类上调用该方法,该基类仅知道其自己的species成员。

如果给您的Cat类一个IntroduceCat()方法,然后在其中打印species并调用它,您将看到“ cat”字符串正在打印。

如果要覆盖派生类中的成员,则必须将该成员标记为virtual基类中的成员,并将override其标记为派生类中的成员。但是您不能对字段执行此操作,因此必须将其设置为属性。

但是您可能只想分配一个不同的值,并且可以在构造函数中进行分配。