三种特别的属性
1.AttributeUsage属性
[System.AttributeUsage(System.AttributeTargets.Class |
System.AttributeTargets.Struct,AllowMultiple=true ,Inherited =true ) ] //Author属性只
能用于类和结构,AllowMultiple是否允许多次用属性,Inherited是这个属性是滞延续到子类。
public class AuthorAttribute : System.Attribute
 {
  private string name;
  public double version;
  public AuthorAttribute(string name)
   {
    this.name = name; version = 1.0;
   }
        public string Name
       {
           get{return name;}
       }
 }
[Author(“张三”, version =2.0)]//张三是Author的构造函数的参数,version是字段
 class SampleClass
 { }
这种属性在我们定义类或者字段时可以通过它的使用能实现不写sql语句就能达到查询、添加、修
改、删除的效果。AttributeUsage属性的使用使我们在类中定义的字段与数据库中的字段得到对应
。通过反射可以得到数据库中的字段。
属性的查看
static void Main()
{
           Type t1 = typeof(SampleClass);
            object[] ArrAtt = t1.GetCustomAttributes(true);//得到SampleClass类中的特性 
      //返回为object类型的数组
            foreach (object o in ArrAtt)
            {               
                AuthorAttribute author=  (AuthorAttribute)o;
                Console.WriteLine(“作者:{0},版本:{1}”,author.Name,author.
version);
            }
}
2.Conditional属性
条件方法必须是类或结构声明中的方法,而且必须具有 void 返回类型。
(1)如果我们要是Msg()方法不执行可以注释#define TRACE_ON 
#define TRACE_ON   //这行标识代码决定着红色代码的执行与否。
using System;
using System.Diagnostics;
namespace R_A_Demo
{
    public class Trace
    {
        [Conditional("TRACE_ON")]//重点注意部分
        public static void Msg(string msg)
        {
            Console.WriteLine(msg);
        }
    }
    public class ProgramClass
    {
        static void Main()
        {
            Trace.Msg(“调试信息”); //注意他的调用方法
            Console.WriteLine(“代码正体");
        }
    }
}
(2)另一种用法
#define TRACE_ON
using System;
using System.Diagnostics;
namespace R_A_Demo
{
    public class Trace
    {
#if TRACE_ON
        public static void Msg(string msg)
        {
            Console.WriteLine(msg);
        }
#endif
    }
    public class ProgramClass
    {
        static void Main()
        {
            Trace.Msg("Now in Main...");
            Console.WriteLine("Done.");
        }
    }
}
这两种用法的区别:第(1)种方法把#define注释之后编译时不会再调用。第(2)种方法在编译
时仍会调用。
3.Obsolete属性
[System.Obsolete(“use class B”)] //类会被在实例化时警告过期
    class A
    {
        public void Method() { }
    }
    class B
    {
        [System.Obsolete("use NewMethod", false )] //方法调用时提示信息
        public void OldMethod() { }
        [System.Obsolete("use NewMethod", true)] //不可编译
        public void NewMethod() { }
    }
要注意false与true的使用。false在编译时可以通过,但是会提示已过期。TRUE则会在编译时都通
不过。