主函数:
#define IsTest
using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
namespace 特性
{
class Program
{
//Obsolete特性,第一个参数的string编译器将会显示给用户
[Obsolete("这个方法被弃用了,使用newMethod代替")]//第二个bool参数可设置函数是否可用
static void oldMethod()
{
}
static void newMethod()
{
}
//Conditional特性
[Conditional("IsTest")] //只有定义了IsTest宏,才会调用test1函数
static void test()
{
}
//DebuggerStepThrough特性
[DebuggerStepThrough] //函数可以跳过调试阶段,当确定函数无BUG时使用
static void test1()
{
}
[Serializable] //声明结构可以被序列化 相反的特性为:[NonSerializable]不可被序列化
static void test2()
{
}
[MyTest] //自定义的特性
static void test3()
{
}
static void Main(string[] args)
{
oldMethod();
}
}
}
自定义特性类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 特性
{
//自定义特性类一般以Attribute结尾
//需要继承自System.Attribute
//一般情况申明为sealed
//一般情况下用来表示目标结构的一些状态(定义一些字段属性)
[AttributeUsage(AttributeTargets.Class)]//表示该特性类可以应用到的程序结构 如委托,事件等
sealed class MyTestAttribute : System.Attribute
{
public string Des { get; set; }
public string Version { get; set; }
public int ID { get; set; }
}
}