【发布时间】:2023-10-30 03:48:01
【问题描述】:
我有一个通过构造函数分配的动态对象Type。这是我的代码的简化版本:
public static void Main(string[] args)
{
var x = new Shirt("Collared");
}
class Shirt {
public dynamic Type = new { };
public string ProblemVariable;
public Shirt() { }
public Shirt(string type) {
ProblemVariable = "Assigned in Constructor";
if (type == "Collared") {
Type = new Type.Collared();
}
}
class Type : Shirt {
public Type() { }
public Type(string value)
{
}
}
class Collared : Type { }
在 Main() 中,调用 x.Type.GetType() 返回我的动态 x.Type 是 Type.Collared。在Type.Collared 中,我想创建一个从基类Shirt 访问字符串ProblemVariable 的函数:
class Collared : Type {
public void GetProblemVariable() {
Console.WriteLine(ProblemVariable);
}
}
这样做会返回一个NullReferenceException。如果我在类定义中将ProblemVariable 分配为"Not modified":
class Shirt {
public string ProblemVariable = "Not modified";
我的函数 GetProblemVariable 将 ProblemVariable 返回为 "Not Modified"。
虽然我显然可以从基类Shirt 访问ProblemVariable,但为什么Type.Collared 没有像构造函数Shirt(string type) 中定义的"Assigned in Constructor"那样返回ProblemVariable?
【问题讨论】:
标签: c# inheritance dynamic constructor