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

C# 是否可以向动态对象运行时的属性添加属性?,c#,dynamic,expandoobject,C#,Dynamic,Expandoobject,我想在动态对象/expando对象运行时的属性中添加一个属性,可以吗 我想做的是: dynamic myExpando = new ExpandoObject(); myExpando.SomeProp = "string"; myExpando.AddAttribute("SomeProp", new MyAttribute()); 有没有可能以这样或那样的方式进行此操作?您可以向动态对象添加一个属性,如下所示: dynamic myExpando = new ExpandoObject(

我想在动态对象/expando对象运行时的属性中添加一个属性,可以吗

我想做的是:

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

有没有可能以这样或那样的方式进行此操作?

您可以向动态对象添加一个属性,如下所示:

 dynamic myExpando = new ExpandoObject();
            myExpando.SomeProp = "string";
            TypeDescriptor.AddAttributes(myExpando, new SerializableAttribute());
要读取属性,应使用以下命令:

 dynamic values = TypeDescriptor.GetAttributes(myExpando);
            for (int i = 0; i < values.Count; i++)
            {
                System.Console.WriteLine(values[i]);
            }
dynamic values=TypeDescriptor.GetAttributes(myExpando);
for(int i=0;i
我不确定您是否可以读取这样的自定义属性。但是,您也可以尝试反射:

 System.Reflection.MemberInfo info = myExpando.GetType();
            object[] attributes = info.GetCustomAttributes(true);
            for (int i = 0; i < attributes.Length; i++)
            {
                System.Console.WriteLine(attributes[i]);
            }
System.Reflection.MemberInfo=myExpando.GetType();
object[]attributes=info.GetCustomAttributes(true);
for(int i=0;i
但是,通过反射,您无法看到已添加的属性,因为属性是静态元数据

TypeDescriptor是.NET FCL提供的元数据引擎。你可以在这里阅读这篇文章:


为什么不运行该代码并查看?您是否签出了
TypeDescriptor
@萨米亚姆:我认为他不希望它起作用,但明确地说,不,它不起作用。结果是:
RuntimeBinderException:'System.Dynamic.ExpandoObject'不包含'AddAttribute'的定义。
也可能help@user2720372:不是重复的。这对属性没有帮助。但这是将属性添加到类型而不是属性。