ExpandoObject object and GetProperty()

后端 未结 1 934
名媛妹妹
名媛妹妹 2021-01-21 04:21

I\'m trying to write a generic utility for use via COM from outside .NET (/skip long story). Anyway, I\'m trying to add properties to an ExpandoObject and I need to get Property

相关标签:
1条回答
  • 2021-01-21 05:05

    While using an ExpandoObject it might look like you can add properties at runtime, it won't actually do that at the CLR level. That's why using reflection to get the property you added at runtime won't work.

    It helps to think of an ExpandoObject as a dictionary mapping strings to objects. When you treat an ExpandoObject as a dynamic variable any invocation of a property gets routed to that dictionary.

    dynamic exp = new ExpandoObject();
    exp.A = "123";
    

    The actual invocation is quite complex and involves the DLR, but its effect is the same as writing

    ((IDictionary<string, object>)exp)["A"] = "123";
    

    This also only works when using dynamic. A strongly typed version of the code above results in a compile-time error.

    var exp = new ExpandoObject();
    exp.A = "123"; // compile-time error
    

    The actual implementation of ExpandoObject can be found here.

    0 讨论(0)
提交回复
热议问题