简体   繁体   English

我可以从实例化的类继承吗?

[英]Can I inherit from an instantiated class?

I'm trying to inherit from an instantiated class. 我正在尝试从实例化的类继承。 Why is the value of Inherited , in the code below, a null value? 为什么在下面的代码中Inherited的值是空值? Is there a way to do this correctly? 有没有办法正确地做到这一点?

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();
        }
    }
}

Inheriting occurs at compile time. 继承发生在编译时。 (Therefore 'Inherited' does not have a value yet) Values are assigned at run-time. (因此'Inherited'还没有值)在运行时分配值。

Inheriting from a class does not inherit the INSTANCE of that class at instantiation of the inherited class. 从类继承不会在继承的类实例化时继承该类的INSTANCE。 Instead, you'd need to pass along the instance of that class. 相反,您需要传递该类的实例。 One option is to inject it into the constructor of class 3 一种选择是将其注入类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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM