C#中的特性,允许向程序的程序集增加元数据,用于保存程序结构信息。
1.Obsolete
Obsolete特性标记方法已被弃用。并在代码编译时,显示警告信息。
[Obsolete("该方法已被弃用")]
static void OldMethod()
{
Console.WriteLine("OldMethod");
}
2.Conditional
Conditional特性,使用或取消方法的调用,执行依赖于指定的预处理标识符。
[Conditional("TEST")]
static void TestMethod()
{
Console.WriteLine("TestMethod");
}
当在定义了#define TEST时,该方法被调用,否则不调用。一般用于调试信息的输出。
3.DebuggerStepThrough
调试代码时,告诉调试器不要进入某些方法。当确定某些方法没有错误的时候,使用该特性。
[DebuggerStepThrough]
static void TestMethod2()
{
Console.WriteLine("TestMethod2");
}
4.调用者信息特性
CallerFilePath 获取调用该方法的文件路径
CallerLineNumber 获取调用该方法的源文件的行号
CallerMemberName 获取调用该方法的方法名
using System;
using System.Runtime.CompilerServices;
namespace CSharpTest
{
class Program
{
//调用者信息特性
static void PrintStr(string str, [CallerFilePath]string file = "", [CallerLineNumber]int line = 0,
[CallerMemberName]string method = "")
{
Console.WriteLine(str);
Console.WriteLine("文件名:" + file);
Console.WriteLine("行号: " + line);
Console.WriteLine("方法名: " + method);
}
static void Main(string[] args)
{
PrintStr("Hello,April");
Console.ReadKey();
}
}
}
运行结果
5.自定义特性
自定义特性类时,需要遵守一些规则:
- 类名称以Attribute结尾
- 继承System.Attribute
- 一般情况下声明为sesealed,不能被继承
- 表示目标结构的状态(包含字段及属性,一般不定义方法)
using System;
namespace CSharpTest
{
[Test("自定义特性类", 1.2)]
class Program
{
[AttributeUsage(AttributeTargets.Class)] //该特性类适用范围
sealed class TestAttribute : Attribute
{
public string Description { get; set; }
public double Version { get; set; }
public TestAttribute(string description, double version)
{
this.Description = description;
this.Version = version;
}
}
static void Main(string[] args)
{
Type type = typeof(Program);
object[] array = type.GetCustomAttributes(false);
TestAttribute attr = array[0] as TestAttribute;
Console.WriteLine("Description: " + attr.Description);
Console.WriteLine("Version: " + attr.Version);
Console.ReadKey();
}
}
}