Get value of c# dynamic property via string

前端 未结 11 1724
孤城傲影
孤城傲影 2020-11-27 11:12

I\'d like to access the value of a dynamic c# property with a string:

dynamic d = new { value1 = \"some\", value2 = \"random\", value3 = \"value\"

11条回答
  •  一整个雨季
    2020-11-27 11:43

    Much of the time when you ask for a dynamic object, you get an ExpandoObject (not in the question's anonymous-but-statically-typed example above, but you mention JavaScript and my chosen JSON parser JsonFx, for one, generates ExpandoObjects).

    If your dynamic is in fact an ExpandoObject, you can avoid reflection by casting it to IDictionary, as described at http://msdn.microsoft.com/en-gb/library/system.dynamic.expandoobject.aspx.

    Once you've cast to IDictionary, you have access to useful methods like .Item and .ContainsKey

提交回复
热议问题