【问题标题】:C# Dynamic object cannot access variable as assigned in base constructorC# 动态对象无法访问在基本构造函数中分配的变量
【发布时间】: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.TypeType.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


    【解决方案1】:

    因为 Type = new Type.Collared();调用基础构造函数 public Shirt() { },而不是 public Shirt(string type),因此没有分配 ProblemVariable。

    【讨论】:

    • 我通过添加构造函数public Collared(string value) { ProblemVariable = value; } 解决了这个问题,并将new Type.Collared() 更改为new Type.Collared(DataToPass),效果很好。
    最近更新 更多