How to access property of anonymous type in C#?

后端 未结 5 1073
南旧
南旧 2020-11-28 02:40

I have this:

List nodes = new List(); 

nodes.Add(
new {
    Checked     = false,
    depth       = 1,
    id          = \"div_\"         


        
      
      
      
5条回答
  •  日久生厌
    2020-11-28 03:20

    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!

    1. o is null, so there is no object at all
    2. o is non-null but doesn't have a property Foo
    3. 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.

提交回复
热议问题