Rob*_*cer 2 c# dynamic expandoobject
我正在尝试编写一个通用实用程序,以从.NET外部通过COM使用(/跳过长篇故事)。无论如何,我试图将属性添加到ExpandoObject,并且我需要获取PropertyInfo结构以传递给另一个例程。
using System.Collections.Generic;
using System.Diagnostics;
using System.Dynamic;
using System.Reflection;
public class ExpandoTest
{
public string testThis(string cVariable)
{
string cOut = "";
ExpandoObject oRec = new ExpandoObject { };
IDictionary<string, object> oDict = (IDictionary<string, object>)oRec;
oDict.Add(cVariable, "Test");
Trace.WriteLine(cVariable);
Trace.WriteLine(oDict[cVariable]);
PropertyInfo thisProp = oRec.GetType().GetProperty(cVariable);
if (thisProp != null)
{
cOut= "Got a property :)";
}
return cOut;
}
}
Run Code Online (Sandbox Code Playgroud)
为什么我总是在thisProp中获得null?我显然不明白,但我一直盯着它看了一天,却一无所获。感谢所有的帮助/批评!
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";
Run Code Online (Sandbox Code Playgroud)
The actual invocation is quite complex and involves the DLR, but its effect is the same as writing
((IDictionary<string, object>)exp)["A"] = "123";
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
The actual implementation of ExpandoObject can be found here.