2

我正在尝试从实例化类继承。为什么Inherited在下面的代码中的值是空值?有没有办法正确地做到这一点?

namespace Sample {
    public class Class1 {
        static void Main() {
            Class2 SecondClass = new Class2();
            SecondClass.StartSomething("hello world");
        }
    }

    public class Class2 {
        public string Inherited;
        public void StartSomething(string value) {
            Inherited = value;
            InheritSomething();
        }
        public void InheritSomething() {
            Class3 ThirdClass = new Class3();
            ThirdClass.DoSomething();
        }
    }

    public class Class3 : Class2 {
        public void DoSomething() {
            Console.WriteLine(Inherited);//when complied Inherited is null
            Console.ReadLine();
        }
    }
}
4

2 回答 2

4

继承发生在编译时。(因此“继承”还没有值)在运行时分配值。

于 2013-10-03T17:11:33.410 回答
0

从类继承不会在被继承类的实例化时继承该类的实例。相反,您需要传递该类的实例。一种选择是将其注入到类 3 的构造函数中

public class Class1
{
    static void Main()
    {
        Class2 SecondClass = new Class2();
        SecondClass.StartSomething("hello world");
    }
}

public class Class2
{
    public string Inherited;
    public void StartSomething(string value)
    {
        Inherited = value;
        InheritSomething();
    }
    public void InheritSomething()
    {
        Class3 thirdClass = new Class3(this);
        thirdClass.DoSomething();
    }
}

public class Class3 : Class2
{
    private Class2 _class2;

    public Class3(Class2 class2)
    {
        _class2 = class2;
    }

    public void DoSomething()
    {
        Console.WriteLine(_class2.Inherited);
        Console.ReadLine();
    }
}
于 2013-10-03T17:28:00.037 回答