简体   繁体   English

是否可以向动态对象运行时的属性添加属性?

[英]Is it possible to add attributes to a property of dynamic object runtime?

I want to add an attribute to property of a dynamic object/expando object runtime, is it possible?我想为动态对象/扩展对象运行时的属性添加一个属性,这可能吗?

What I would like to do is:我想做的是:

dynamic myExpando = new ExpandoObject();
myExpando.SomeProp = "string";
myExpando.AddAttribute("SomeProp", new MyAttribute());

Is it possible to do that in one way or another?有可能以一种或另一种方式做到这一点吗?

You can add an attribute to a dynamic object like this:您可以像这样向动态对象添加属性:

 dynamic myExpando = new ExpandoObject();
            myExpando.SomeProp = "string";
            TypeDescriptor.AddAttributes(myExpando, new SerializableAttribute());

To read the attributes you should use this:要阅读您应该使用的属性:

 dynamic values = TypeDescriptor.GetAttributes(myExpando);
            for (int i = 0; i < values.Count; i++)
            {
                System.Console.WriteLine(values[i]);
            }

I am not sure you can read custom attributes like that.我不确定您是否可以读取这样的自定义属性。 However you can also try reflection:但是,您也可以尝试反射:

 System.Reflection.MemberInfo info = myExpando.GetType();
            object[] attributes = info.GetCustomAttributes(true);
            for (int i = 0; i < attributes.Length; i++)
            {
                System.Console.WriteLine(attributes[i]);
            }

However, with reflection you cannot see the attribute that you have been added because attributes are static metadata.但是,通过反射,您无法看到已添加的属性,因为属性是静态元数据。

TypeDescriptor is a metadata engine provided by the .NET FCL. TypeDescriptor 是 .NET FCL 提供的元数据引擎。 You can read the article here:你可以在这里阅读这篇文章:

http://blogs.msdn.com/b/parthopdas/archive/2006/01/03/509103.aspx http://blogs.msdn.com/b/parthopdas/archive/2006/01/03/509103.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM