zoukankan      html  css  js  c++  java
  • 使用TypeDescriptor给类动态添加Attribute【转】

    源文 : http://www.cnblogs.com/bicker/p/3326763.html

    给类动态添加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());
                }   
    复制代码
  • 相关阅读:
    tracert命令与tracert (IP地址)-d有什么区别?
    linux下通过进程名查看其占用端口
    Union和Union All的区别
    外连接、内连接
    Linux 删除文件夹和文件的命令(强制删除包括非空文件)
    linux查看当前目录
    Linux chmod命令及权限含义
    MySQL的if,case语句
    case when
    java生成验证码图片
  • 原文地址:https://www.cnblogs.com/mazhenyu/p/4613172.html
Copyright © 2011-2022 走看看