Frage

I have this code:

object test = new {a = "3", b = "4"};
Console.WriteLine(test); //I put a breakpoint here

How can I access a property of test object? When I put a breakpoint, visual studio can see the variables of this object... Why can't I? I really need to access those.

War es hilfreich?

Lösung 2

If you cannot use static typing for your anonymous class, you can use dynamic, like this:

static object MakeAnonymous() {
    return new {a = "3", b = "4"};
}
static void Main(string[] args) {
    dynamic test = MakeAnonymous();
    Console.WriteLine("{0} {1}", test.a, test.b);
}

The downside to this approach is that the compiler is not going to help you detect situations when a property is not defined. For example, you could write this

Console.WriteLine("{0} {1}", test.abc, test.xyz); // <<== Runtime error

and it would compile, but it would crash at runtime.

Andere Tipps

If you want the compiler support, then you should use a var and not object. It should recognize that you have an object with properties a and b. You are downcasting to an object in the above code, so the compiler will only have object properties

var test = new {a = "3", b = "4"};
Console.WriteLine(test.a); //I put a breakpoint here

If you cannot use var for whatever reason, then you can look into dynamic or this grotty hack for passing anonymous types from Skeet

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top