您是第欢迎光临我的主页位访客
浩凡儿
天行健,君子以自强不息;地势坤,君子以厚德载物!


概念:

        1书中解释:在.NET中编译器的任务之一是为所有定义和引用的类型生成元数据描述。除了程序集中标准的元数据外,.NET平台允许程序员使用特性(attribute)把更多的元数据嵌入到程序集中。简而言之,特性就是用于类型,成员,程序集或模块的代码注解。

       2:个人理解:所谓的特性其实就是标注性的东西,它标注被所标注的类型是什么样子的,就像是军衔标注一样你是一等兵,他是二等兵,所以你两的

也就有所不同。

 

简单用法:

View Code
  [Serializable][Obsolete("Use another vehicle")]
//或是这样用[Serializable,Obsolete("Use another vehicle")]
public class Motorcycle
{
//可是这个字段不能被持久化
[NonSerialized]
float weightOfCurrentPassengers;

//这些是要被持久化
bool hasRadioSystem;
public bool hasHeadSet;
bool hasSissyBar;
}

 

而在Main()方法中这样调用:

View Code
 class Program
{
static void Main(string[] args)
{
Motorcycle mc = new Motorcycle();
mc.hasHeadSet = true;
Console.WriteLine("mc.HasHeadSet is {0}",mc.hasHeadSet.ToString());
Console.ReadLine();

}
}



定制自定义特性:

    其实我们完全可以自己定义特性,只是有一些规则:它必须继承Attibute,或派生自它的类型。如下:

 

View Code
  [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]
public sealed class VehicleDescriptionAttribute : Attribute
{
public string Description { set; get; }
public VehicleDescriptionAttribute(string vehicleDesciption)
{
this.Description = vehicleDesciption;
}
public VehicleDescriptionAttribute() { }
}
[Serializable]
//使用Named Property命名属性为Description赋值。
[VehicleDescription(Description = "My rocking Harley")]
public class MotoRcycle
{

}
[SerializableAttribute]
[VehicleDescription("The old gray mare, she ain't what she used to be ...")]
public class HorseAndBuggy
{

}
[VehicleDescription("A very long,slow,but feature-rich auto")]
public class Winnebago
{

}


 

在上边的这行代码: [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, Inherited = false)]

是对于我们定制特性的限制,默认情况下,自定义的特性是适用于所有的类型的而而有些
     时候,我们只想让他适用某些特定的类型上(类,结构,参数,接口等)
     这时就有用到AttributeTargets枚举类型来限定我们自定义的特性了,它的定义如下:
     public enum AttributeTargets
     {
       All,Assembly,Class,Constuctor,Delegate,Enum,
     Event,Field,genericParameter,Interface,Method,
     Module,Parameter,Property,ReturnValue,Struct
     }
     限定时我们还要用[AttributeUsage]

 

而在Main()方法中:

View Code
  static void Main(string[] args)
{
Console.WriteLine("*** Value of DefineAttribute ***\n");
ReflectOnAttributeUsingEarlyBinding();
Console.ReadLine();
}
private static void ReflectOnAttributeUsingEarlyBinding()
{
Type t=typeof(Winnebago);
object[] customAtts = t.GetCustomAttributes(false);
foreach (VehicleDescriptionAttribute v in customAtts)
{
Console.WriteLine("——》 {0}",v.Description);
}
}

 

运行结果:

好了关于特性就写这么多了。

posted on 2012-03-19 09:56  浩凡儿  阅读(1442)  评论(0编辑  收藏  举报