我正在尝试从实例化的类继承。为什么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();
}
}
}
答案 0 :(得分:4)
继承发生在编译时。 (因此'继承'还没有值) 值在运行时分配。
答案 1 :(得分:0)
继承自类不会在继承类的实例化时继承该类的INSTANCE。相反,您需要传递该类的实例。一种选择是将其注入到第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();
}
}