特性:给类或者方法添加一些标签信息。比如我们在调试代码程序的时候为类和方法注明调试事件,调试人以及调试时间等信息。
1.根据定义方式的不同,特性分为系统提供的特性以及自定义的特性。
系统提供的特性:
(1)Conditional:编译时,按照给出的条件决定方法是否执行。 debug 时打印调试信息,release 时取消打印。(Debug,开发测试的一种模式;Release,发布程序编译的一种模式)
#define Hello//预处理指令,加上后,才表示要执行hello方法
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AtrributeTest
{
internal class Program
{
static void Main(string[] args)
{
fun1("fun1---");
Console.ReadKey();
}
static void fun1(string info)
{
Console.WriteLine(info);
MyAtrribute.function1("debug---");
MyAtrribute.hello("hello----");
}
}
public class MyAtrribute
{
[Conditional("DEBUG")]
public static void function1(string info)//Debug模式下才执行
{
Console.WriteLine(info);
}
[Conditional("Hello")]
public static void hello(string info)//加了预定义指令才执行
{
Console.WriteLine(info);
}
}
}
(2)Obsolte:当程序修改时,需要弃用某个方法,使用 Obsolete 做为标识。它标记了不应被使用的程序实体。它可以让您通知编译器丢弃某个特定的目标元素。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AtrributeTest
{
internal class Program
{
static void Main(string[] args)
{
fun1("fun1---");
fun2("fun2---");
Console.ReadKey();
}
static void fun1(string info)
{
Console.WriteLine(info);
}
[Obsolete("Don't use Old Method",true)] //加了true表示在使用该方法时,编译器会直接报错
static void fun2(string info)
{
Console.WriteLine(info);
}
}
}
自定义特性:通过 AttributeUsage 进行定义,通常情况下就是写一个类继承自 Attribute。当然标签特性也要加上。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AtrributeTest
{
internal class Program
{
static void Main(string[] args)
{
}
}
//自定义Attribute标签
//AllowMultiple在这里表示同一个类上是否只能放一个Attribute
//Inherited表示Class被继承的时候,是否继承Attribute
[AttributeUsage(AttributeTargets.Class,AllowMultiple =false,Inherited =false)]
public class HelpAttribute : System.Attribute
{
protected string description;
public HelpAttribute(string descriptionInfo)
{
this.description = descriptionInfo;
}
public string Description
{
get { return this.description; }
}
private string name;
public string Name
{
set { this.name = value; }
get { return this.name; }
}
private int age;
public int Age
{
set { this.age = value; }
get { return this.age; }
}
}
//给MyClass加上了自定义的Attribute标签信息
[HelpAttribute("this is a do-nothing class",Name ="Peter",Age =18)]
public class MyClass
{
}
}
注:自定义属性可以适用的情况,All表示可以被所有情况适用,Assembly表示适用于程序集,Class表示适用于类,其他的都差不多
结语:合抱之木,生于毫末;九层之台,起于累土;千里之行,始于足下。