简体   繁体   中英

C# Dynamic object cannot access variable as assigned in base constructor

I have a dynamic object Type that I assign via a constructor. Here is a simplified version of my code:

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 { }

In Main(), calling x.Type.GetType() returns that my dynamic x.Type is a Type.Collared . In Type.Collared , I would like to create a function that accesses string ProblemVariable from base class Shirt :

class Collared : Type {

    public void GetProblemVariable() {
        Console.WriteLine(ProblemVariable);
    }

}

Doing so returns a NullReferenceException . If I assign ProblemVariable as "Not modified" in my class definition:

class Shirt {

    public string ProblemVariable = "Not modified";

My function GetProblemVariable returns ProblemVariable as "Not Modified" .

While I am obviously able to access ProblemVariable from base class Shirt , why does Type.Collared not return ProblemVariable as "Assigned in Constructor" as defined in constructor Shirt(string type) ?

Because Type = new Type.Collared(); calls base constructor public Shirt() { }, not public Shirt(string type), so ProblemVariable is not assigned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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