使用TypeDescriptor給類動態新增Attribute

weixin_30924079發表於2020-04-04

給類動態新增Attribute一直是我想要解決的問題,從msdn裡找了很久,到Stack Overflow看了不少文章,算是最終有了答案。

先是有這樣的一段解釋

Attributes are static metadata. Assemblies, modules, types, members, parameters, and return values aren't first-class objects in C# (e.g., the System.Type class is merely a reflected representation of a type). You can get an instance of an attribute for a type and change the properties if they're writable but that won't affect the attribute as it is applied to the type.

從這裡看,想要實現動態新增Attribute就是不可能做到的。哈哈,被標題坑了吧。

好吧,但是我還是找到了一個東西System.ComponentModel.TypeDescriptor,這個號稱可以新增Attribute到類、物件中去的類。TypeDescriptor裡有方法:AddAttributes,可以把Attribute新增到類上。但是隻有一個問題,新增上去的Attribute,只能通過TypeDescriptor來取到。

           /*
             *    現在需要給simpleObject新增attribute
             */
            TypeDescriptor.AddAttributes(typeof(targetObject), new simpleAttribute(new targetObject()));
            AttributeCollection collection = TypeDescriptor.GetAttributes(typeof(targetObject));
            simpleAttribute attr = ((simpleAttribute)collection[typeof(simpleAttribute)]);
            if (attr != null)
            {
                MessageBox.Show(attr.ToString());
            }   

 

轉載於:https://www.cnblogs.com/bicker/p/3326763.html

相關文章