我想为动态对象/ expando对象运行时的属性添加属性,是否可能?
我想做的是:
dynamic myExpando = new ExpandoObject();
myExpando.SomeProp = "string";
myExpando.AddAttribute("SomeProp", new MyAttribute());
Run Code Online (Sandbox Code Playgroud)
是否有可能以这种或那种方式做到这一点?
您可以向动态对象添加属性,如下所示:
dynamic myExpando = new ExpandoObject();
myExpando.SomeProp = "string";
TypeDescriptor.AddAttributes(myExpando, new SerializableAttribute());
Run Code Online (Sandbox Code Playgroud)
要读取属性,您应该使用以下命令:
dynamic values = TypeDescriptor.GetAttributes(myExpando);
for (int i = 0; i < values.Count; i++)
{
System.Console.WriteLine(values[i]);
}
Run Code Online (Sandbox Code Playgroud)
我不确定您是否可以读取这样的自定义属性。不过你也可以尝试反射:
System.Reflection.MemberInfo info = myExpando.GetType();
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i++)
{
System.Console.WriteLine(attributes[i]);
}
Run Code Online (Sandbox Code Playgroud)
但是,通过反射,您无法看到已添加的属性,因为属性是静态元数据。
TypeDescriptor 是 .NET FCL 提供的元数据引擎。你可以在这里读这篇文章:
http://blogs.msdn.com/b/parthopdas/archive/2006/01/03/509103.aspx
| 归档时间: |
|
| 查看次数: |
5244 次 |
| 最近记录: |