C#特性学习与使用(为枚举定义Description)

转自: http://blog.csdn.net/nndtdx/article/details/6905802

C#特性

以前的时候,用过C#中的特性,但只是会用,什么原理,有什么用这些问题不清楚,今天就腾出时间,学习了一下。

C#中的特性使用Attribute描述。在使用时,就像是java中的批注一样。不过C#使用中括号。特性用来描述我们的数据。编译器能够识别这些特性,以附加信息的形式存放在生成的元数据中,供clr使用。

下边看一个简单的应用

[csharp]  view plain copy print ?
  1. static void Main(string[] args)  
  2.  {  
  3.            DisplayRunningMsg();  
  4.             DisplayDebugMsg();  
  5.             Trace("方法执行到结尾了!!");  
  6.             Console.Read();  
  7.   
  8. }  
  9.  [DllImport("User32.dll")]  
  10.  public static extern int MessageBox(int hParent, string msg, string Caption, int type);  
  11.         [Conditional("DEBUG")]  
  12.         private  static  void DisplayRunningMsg()  
  13.         {  
  14.             Console.WriteLine("This is debug");  
  15.             Console.WriteLine("开始运行Main子程序。当前时间是"+DateTime.Now);  
  16.         }  
  17.   
  18.         [Conditional("DEBUG")]  
  19.         [Obsolete]  
  20.         private  static  void DisplayDebugMsg()  
  21.         {  
  22.             Console.WriteLine("该方法已经废弃啦!!!");  
  23.         }  

DllImport特新允许我们引入一个外部的dll,下边做一个函数的声明,我们就可以调用了。

Conditional属性表示在该种条件下就执行下边的代码 所以[Conditional("DEBUG")]此种标识的方法就只有在调试的时候才会在执行。   [Obsolete]特性标记该方法已经废弃。

运行上述代码输出(在debug模式下)



看的出来程序执行了[Conditional("DEBUG")]标记的方法。如果我们debug改为release,那么再次执行



程序并没有执行上述方法。看的出来,由于特性[Conditional("DEBUG")]标记,是的在release模式下,代码并没有运行其标记的函数。那么,我们就可以利用这个做一个error trace,使其只在debug的模式下输出当前错误信息,包括行号,,方法名,位置等。这里要用到 stacktrace类。

Ok,说到这里,你应该对特性有了以最最基本的了解。

那么,究竟什么是特性呢?

其实特性也是一个类。比如[Conditional("DEBUG")],就是构造了以Conditional对象(调用构造方法public Conditional(string type), 对,DllImport("User32.dll")对应的也有一个类DllImport.

下边我们自定义一个特性,你就会明白很多。

首先需要定一个一个类 ,该类需要集成Attribute,使其成为一个特性。.NET约定特性类都已Attribute结尾。然后在该类中定义一下字段和属性,完成构造。

代码如下

[csharp]  view plain copy print ?
  1. [AttributeUsage(AttributeTargets.All,AllowMultiple = true,Inherited = true)]  
  2.     class TrackerAttribute:Attribute  
  3.     {  
  4.           
  5.         private string opUsername;  
  6.         private string opName;  
  7.         private DateTime dateTime;  
  8.         private string note;  
  9.   
  10.         public  TrackerAttribute(string  opUsername,string  opName,string date)  
  11.         {  
  12.             this.opUsername = opUsername;  
  13.             this.opName = opName;  
  14.             this.dateTime = DateTime.Parse(date);  
  15.         }  
  16.   
  17.         //位置参数,通过构造函数传递值  
  18.         public string  OpUsername  
  19.         {  
  20.             get { return opUsername; }  
  21.         }  
  22.   
  23.         public  string  OpName  
  24.         {  
  25.             get { return opName; }  
  26.         }  
  27.   
  28.         public  DateTime DateTime  
  29.         {  
  30.             get { return dateTime; }  
  31.         }  
  32.   
  33.         //命名参数,提供set  
  34.         public string  Note  
  35.         {  
  36.             get { return note; }  
  37.             set { note = value; }  
  38.         }  
  39.   
  40.         public override string ToString()  
  41.         {  
  42.             return "操作人" + opUsername + "操作名" + opName + "时间" + dateTime + "备注" + note;  
  43.         }  
  44.     }  

嗯,对,他和普通的类几乎没什么差别,只不过继承于Attribute。然后他本身又有一些特性。我们做逐一介绍

我们在类TrackerAttribute 定义了几个字段,完成了构造函数TrackerAttribute(string opUsername,string  opName,stringdate)

那么我么在使用的时候就需要写[Tracker(“opusername”,”opname”,”2011-10-2600:04”,note=”这是备注”)],嗯,是的,使用类型(参数值,参数值)的方法完成了该对象的构造,即调用了该类的构造函数。构造函数里与字段对应的参数叫做位置参数,因为写的时候必须位置一一与源构造函数相同,其他不通过构造函数传入参数传递的,叫做命名参数使用字段名=字段值 的形式赋值。这样完成函数构造和一些属性的赋值。一般情况下,我们将位置参数提供get访问,而命名参数则提供get和set,因为位置参数已经能够同感哦构造函数访问赋值了。

这个特性类上边还有几个特性,AttributeTargets表示当前特性的作用范围,他是一个位标记的枚举,比如all,field,method,标记过后,智能在相应的地方做该特性书写。比如指定枚举是作用与字段,那么如果该特性写在类上边,就会报错。

如上,你的特性类就完成了。

这样你就可以在其他方法上做该特性的标记了。

我们定义了特性,最重要的还是要获得该特性中的值。下边是获得的方法

[csharp]  view plain copy print ?
  1. Type type = typeof(Program);  
  2.             object[] objects = type.GetCustomAttributes(false);  
  3.             foreach (var o in objects)  
  4.             {  
  5.                 TrackerAttribute trackerAttribute = o as TrackerAttribute;  
  6.                 if (trackerAttribute != null)  
  7.                     Console.WriteLine(trackerAttribute.ToString());  
  8.                 else  
  9.                 {  
  10.                     Console.WriteLine("获得对象为空");  
  11.                 }  
  12.             }  

type.GetCustomAttributes(false);该方法将会获得该类上的所有特性标记,返回的是一个object的数组,你可以遍历,然后转换为你的指定特性,访问相应字段即可。同样,你也可以通过type.getMethods()[0] 获得一个methodinfo对象,然后调用该methodinfo对象的GetCustomAttributes方法即可。

 

介绍了如上的这些,我们利用特性,实现为枚举增加一个获得其描述的功能。

例如定义枚举

MyEnummyenum=MyEnum.TypeA 调用myenum.ToDescription 可以得到字符串 类型A。(转者注:MyEnum myenum=MyEnum.TypeA)

我们可以想到定一个描述特性,然后在各个枚举元素上,做该特性的标记,然后提供扩展方法,访问该特性,取得该特性值。

代码如下

枚举定义

[csharp]  view plain copy print ?
  1. public enum MyType  
  2.     {  
  3.         [Description("A类型")]  
  4.         TypeA,  
  5.         [Description("B类型")]  
  6.         TypeB,  
  7.         [Description("C类型")]  
  8.         TypeC  
  9.     }  

特性类DescriptionAttribute定义如下

[csharp]  view plain copy print ?
  1. [AttributeUsage(AttributeTargets.Field,AllowMultiple =true,Inherited = true)]  
  2.   class DescriptionAttribute:Attribute  
  3.   {  
  4.       private string description;  
  5.       public  string Description  
  6.       {  
  7.           get { return description; }  
  8.       }  
  9.   
  10.       public  DescriptionAttribute(String description)  
  11.       {  
  12.           this.description = description;  
  13.       }  
  14.   }  

指定该特性只用于字段,定义DescriptionAttribute(String description)构造函数。

Ok,现在还缺少枚举的ToDescription方法,C#中的枚举是不支持定义方法的。

我们可以为其做一个扩展方法

扩展方法需要一个静态类,参数前要加this ,同时也指定了被扩展的对象,调用时可使用扩展对像的实例调用,也可以使用该静态类来调用。详细内容可参考http://www.cnblogs.com/sunrack/articles/1073759.html

 

扩展类如下

[csharp]  view plain copy print ?
  1. public  static class Extension  
  2.    {  
  3.   
  4.        public  static string ToDescription(this MyType myEnum)  
  5.        {  
  6.            Type type = typeof (MyType);  
  7.            FieldInfo info= type.GetField(myEnum.ToString());  
  8.             DescriptionAttribute descriptionAttribute= info.GetCustomAttributes(typeof (DescriptionAttribute), true)[0] as DescriptionAttribute;  
  9.             if (descriptionAttribute != null)  
  10.                 return descriptionAttribute.Description;  
  11.             else  
  12.                 return type.ToString();  
  13.        }  
  14.    }  


这样MyType就多了一个ToDescription的方法,返回的值就是对应的特性值。

在main方法中

            MyTypemyType = MyType.TypeB;

            Console.WriteLine(myType.ToDescription());

控制台输出 B类型 达到了我们想要的效果。

这个方法还是很有用的。

 

从上边可以看出,我们如果要为一些类添加一些附加的信息,1. 这些附加信息在现实意义与该对象并不是具有真正的对象与属性关系,2. 无法在原来的,里边添加字段,或者加入字段后很难处理。这两种情况之一,都可以使用特性。随后,在IL中看一下,掉用特性时,编译器都做了什么事。晚了,该睡了。


2011/10/31 补:

 

今天用IL DASM 工具,查看了一下生成的IL代码,取出其中部分。

枚举MyType定义如下

[plain]  view plain copy print ?
  1. .class public auto ansi sealed caILStudy.MyType  
  2.        extends [mscorlib]System.Enum  
  3. {  
  4.   .field public specialname rtspecialname int32 value__  
  5.   .field public static literal valuetype caILStudy.MyType TypeA = int32(0x00000000)  
  6.   .custom instance void caILStudy.DescriptionAttribute::.ctor(string) = ( 01 00 07 41 E7 B1 BB E5 9E 8B 00 00 )             // ...A........  
  7.   .field public static literal valuetype caILStudy.MyType TypeB = int32(0x00000001)  
  8.   .custom instance void caILStudy.DescriptionAttribute::.ctor(string) = ( 01 00 07 42 E7 B1 BB E5 9E 8B 00 00 )             // ...B........  
  9.   .field public static literal valuetype caILStudy.MyType TypeC = int32(0x00000002)  
  10.   .custom instance void caILStudy.DescriptionAttribute::.ctor(string) = ( 01 00 07 43 E7 B1 BB E5 9E 8B 00 00 )             // ...C........  
  11. } // end of class caILStudy.MyType  

看的出来,枚举在IL中,任然会被转换成为一个类,各个类型是其字段。然而特性的定义是custom instance,我的IL语言功底不行,只能解释到这里了。

查看main方法中的代码


[plain]  view plain copy print ?
  1. .method private hidebysig static void  Main(string[] args) cil managed  
  2.  {  
  3.    .entrypoint  
  4.    // Code size       14 (0xe)  
  5.    .maxstack  1  
  6.    .locals init ([0] valuetype caILStudy.MyType myType)  
  7.    IL_0000:  ldc.i4.1  
  8.    IL_0001:  stloc.0  
  9.    IL_0002:  ldloc.0  
  10.    IL_0003:  call       string caILStudy.Extension::ToDescription(valuetype caILStudy.MyType)  
  11.    IL_0008:  call       void [mscorlib]System.Console::WriteLine(string)  
  12.    IL_000d:  ret  
  13.  } // end of method Program::Main  

看来,本质上仍然是调用扩展方法,将枚举参数传递进去,输出结果。Ok,就到这里吧。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值