http://blog.csdn.net/litao2/article/details/17633107

使用反射访问: 自定义属性的信息和对其进行操作的方法。

一、实例1

1、代码:

如:System.Attribute[] attrs=System.Attribute.GetCustomAttributes(typeof(FirstClass));

  1. namespace ConsoleApplication1
  2. {
  3. class Program
  4. {
  5. static void Main(string[] args)
  6. {
  7. PrintAuthorInfo(typeof(FirstClass));
  8. PrintAuthorInfo(typeof(SecondClass));
  9. PrintAuthorInfo(typeof(ThirdClass));
  10. Console.ReadKey();
  11. }
  12. private static void PrintAuthorInfo(System.Type t)
  13. {
  14. System.Console.WriteLine("\n类型的 System.Type 对象是:{0}", t);
  15. System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  //反射获得用户自定义属性
  16. foreach (System.Attribute attr in attrs)
  17. {
  18. if (attr is Author)
  19. {
  20. Author a = (Author)attr;
  21. System.Console.WriteLine("   名称:{0}, 版本: {1:f}", a.GetName(), a.version);
  22. }
  23. }
  24. }
  25. }
  26. [System.AttributeUsage(System.AttributeTargets.Class |
  27. System.AttributeTargets.Struct,
  28. AllowMultiple = true)
  29. ]//自定义特性类(应用特性的程序元素(是类或结构),程序元素可以指定多个特性)
  30. public class Author : System.Attribute
  31. {
  32. string name;
  33. public double version;
  34. public Author(string name)
  35. {
  36. this.name = name;
  37. version = 1.0;  // Default value
  38. }
  39. public string GetName()
  40. {
  41. return name;
  42. }
  43. }
  44. [Author("H. Ackerman")]
  45. public class FirstClass
  46. {
  47. // ...
  48. }
  49. // No Author attribute
  50. public class SecondClass
  51. {
  52. // ...
  53. }
  54. [Author("H. Ackerman"), Author("M. Knott", version = 2.0)]
  55. public class ThirdClass
  56. {
  57. //程序元素可以指定多个特性
  58. }
  59. }

2、效果:

二、实例2

1、代码

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Linq.Expressions;
  6. using System.Collections.Specialized;
  7. using System.Reflection;
  8. using System.Data.Linq.Mapping;
  9. namespace ConsoleApplication1
  10. {
  11. class Program
  12. {
  13. static void Main(string[] args)
  14. {
  15. PropertyInfo[] propertys = typeof(FirstClass).GetProperties();//返回FirstClass的所有公共属性
  16. if (propertys != null && propertys.Length > 0)
  17. {
  18. foreach (PropertyInfo p in propertys)
  19. {
  20. object[] objAttrs = p.GetCustomAttributes(typeof(ColumnAttribute), true);//获取自定义特性
  21. //GetCustomAttributes(要搜索的特性类型,是否搜索该成员的继承链以查找这些特性)
  22. if (objAttrs != null && objAttrs.Length > 0)
  23. {
  24. ColumnAttribute attr = objAttrs[0] as ColumnAttribute;
  25. Console.WriteLine("自定义特性Name:"+p.Name+", 元数据:"+attr);
  26. }
  27. };
  28. }
  29. Console.ReadKey();
  30. }
  31. }
  32. public class FirstClass
  33. {
  34. private int _newsid = 0;
  35. /// <summary>
  36. /// 主键
  37. /// </summary>
  38. [Column(Name = "NewsId", DbType = "int", IsPrimaryKey = true, CanBeNull = false, IsDbGenerated = true)]
  39. public int NewsId
  40. {
  41. get
  42. {
  43. return this._newsid;
  44. }
  45. set
  46. {
  47. this._newsid = value;
  48. }
  49. }
  50. private string _newsimage = string.Empty;
  51. /// <summary>
  52. /// 资讯标题图片
  53. /// </summary>
  54. [Column(Name = "NewsImage", DbType = "varchar", IsPrimaryKey = false, CanBeNull = false, IsDbGenerated = false)]
  55. public string NewsImage
  56. {
  57. get
  58. {
  59. return this._newsimage;
  60. }
  61. set
  62. {
  63. this._newsimage = value;
  64. }
  65. }
  66. }
  67. }

2、效果

其他:

FullName(获得System.Type的完全限定名,包括命名空间)

三、实例3 (设置指定实例 属性 的值)

  1. FirstClass fClass = new FirstClass();
  2. PropertyInfo pInstance = typeof(FirstClass).GetProperty("NewsId");//搜索具有指定名称的公共属性
  3. pInstance.SetValue(fClass, 11, null);//设置指定实例 属性 的值
  4. Console.WriteLine("新闻ID:"+fClass.NewsId);
  5. Console.WriteLine("新闻图片:"+fClass.NewsImage);

//在4px的库内操作获取打印机

trv_LabelInvoice.Nodes.Clear();

string strText = string.Empty;
FieldInfo[] fields = typeof(EnumPrintName).GetFields();
foreach (FieldInfo field in fields)
{
strText = field.Name;

object[] arrAttributes = field.GetCustomAttributes(typeof(Attribute), true);
if (arrAttributes != null)
{
EnumAttribute objEnumAttribute = arrAttributes.FirstOrDefault(x => x.GetType().Name.Equals(typeof(EnumAttribute).Name)) as EnumAttribute;
if (objEnumAttribute != null)
{
strText = objEnumAttribute.Description;
}
}

if (trv_LabelInvoice.Nodes.IndexOfKey(field.Name) < 0)
{
trv_LabelInvoice.Nodes.Add(field.Name, strText);
}
}

C# 反射通过GetCustomAttributes方法,获得自定义特性的更多相关文章

  1. c#通过反射获取类上的自定义特性

    c#通过反射获取类上的自定义特性 本文转载:http://www.cnblogs.com/jeffwongishandsome/archive/2009/11/18/1602825.html 下面这个 ...

  2. .NET C#利用反射获取类文件以及其中的方法&属性 并获取类及方法上的特性

    了解C#特性类并声明我们自己的特性类[AttributeTest]代码如下 using System; namespace AttributeTest { /* 特性说明 特性本质是一个继承和使用了系 ...

  3. Attribute自定义特性+Asp.net MVC中的filter详解

    转载自:http://blog.csdn.net/wangyy130/article/details/44241957 一.filter简介 在了解自定义特性前,先引入一个概念filter,它是MVC ...

  4. 【.net 深呼吸】自定义特性(Attribute)的实现与检索方法

    在.net的各个语言中,尤其是VB.NET和C#,都有特性这一东东,具体的概念,大家可以网上查,这里老周说一个非标准的概念——特性者,就是对象的附加数据.对象自然可以是类型.类型成员,以及程序集. 说 ...

  5. C# winform利用反射和自定义特性加载功能模块(插件式开发)

    由于在实际的工作中, 碰见这样的一个问题: 一个软件, 销售给A客户 他需要所有功能, 但是销售给B客户, 他只需要其中的一部分, 1.如果我们在实际的开发过程中, 没有把一些功能模块区分开来的话, ...

  6. C#反射与特性(七):自定义特性以及应用

    目录 1,属性字段的赋值和读值 2,自定义特性和特性查找 2.1 特性规范和自定义特性 2.2 检索特性 3,设计一个数据验证工具 3.1 定义抽象验证特性类 3.2 实现多个自定义验证特性 3.3 ...

  7. C#提高--------------获取方法返回值的自定义特性(Attribute)

    .NET(C#):获取方法返回值的自定义特性(Attribute) 转载 2013年05月08日 10:54:42 1456 来自:http://www.cnblogs.com/mgen/archiv ...

  8. NPOI+反射+自定义特性实现上传excel转List及验证

    1.自定义特性 [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public ...

  9. 反射_IsDefined判断方法上有自定义的标签

    在.NET 4.0(当然也包括4.0以前的版本)下,用反射判断某个方法是否运用了自定义Attribute时,可以通过调用MethodInfo的IsDefined()方法进行确认.当然,IsDefine ...

随机推荐

  1. 【BZOJ4849】[Neerc2016]Mole Tunnels 模拟费用流

    [BZOJ4849][Neerc2016]Mole Tunnels Description 鼹鼠们在底下开凿了n个洞,由n-1条隧道连接,对于任意的i>1,第i个洞都会和第i/2(取下整)个洞间 ...

  2. 统计TCP网络连接情况

    #!/bin/bash metric=$1 tmp_file=/tmp/tcp_status.txt /bin/netstat -an|awk '/^tcp/{++S[$NF]}END{for(a i ...

  3. TFS二次开发-基线文件管理器(2)-TFS登录

    首先需要做一个TFS的登录. 以前的文章是使用的DomainProjectPicker 最新的VS里面使用的是TeamProjectPicker 首先可以在WinForm程序上写一个Button,然后 ...

  4. python模块学习(一)

    模块,用一砣代码实现了某个功能的代码集合. 类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合.而对于一个复杂的功能来,可能需要多个函数才 ...

  5. SpringMVC 课纲

    SpringMVC 课纲 第一章 SpringMVC 架构 一个简单的 web 项目,校验器 SpringMVC 组件及相互关系 第二章 数据绑定 form标签库 第三章 Converter 和 Fo ...

  6. PyNN standard model(转)

    PyNN standard model 转自http://blog.csdn.net/qq_34886403/article/details/76667477

  7. SAP内存、ABAP内存、共享内存的 区别

    区别: (1)SAP内存使用 SET/GET parameters 方法: SET  PARAMETER  ID  ‘MAT’ field P_MATNR. GET  PARAMETER  ID  ‘ ...

  8. corethink功能模块探索开发(四)让这个模块跑起来

    让这个模块跑起来,太费劲了,多半原因是自己太粗心,opencmf.php中“uid”写成了“pid”,de了好几天的bug也没有搞出来,又加上最近发生了些事(brokenhearted)... 上报错 ...

  9. IE浏览器连不上网,其他浏览器可以

    周末因工作需要,需用IE浏览器.结果发现IE连不上网,而其他浏览器正常上网. 首先排查不是网络连接问题. 又重启了一下网络连接.禁用---->启用. 还是不好使.(最后找到原因是DNS设置问题. ...

  10. predis操作大全

    predis是php连接redis的操作库,由于它完全使用php编写,大量使用命名空间以及闭包等功能,只支持php5.3以上版本,故实测性能一般,每秒25000次读写,相信改换c语言编写的php扩展后 ...