If you're storing the object as type object
, you need to use reflection. This is true of any object type, anonymous or otherwise. On an object o, you can get its type:
Type t = o.GetType();
Then from that you look up a property:
PropertyInfo p = t.GetProperty("Foo");
Then from that you can get a value:
object v = p.GetValue(o, null);
This answer is long overdue for an update for C# 4:
dynamic d = o;
object v = d.Foo;
And now another alternative in C# 6:
object v = o?.GetType().GetProperty("Foo")?.GetValue(o, null);
Note that by using ?.
we cause the resulting v
to be null
in three different situations!
o
is null
, so there is no object at all
o
is non-null
but doesn't have a property Foo
o
has a property Foo
but its real value happens to be null
.
So this is not equivalent to the earlier examples, but may make sense if you want to treat all three cases the same.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…