1. [Obsolete] -- 把方法标记为弃用
[Obsolete]
public static void Test1(){}
[Obsolete("这个方法弃用了,请使用最新的XXX方法")]
public static void Test2(){}
2. [Conditional("宏名称")] -- 只有定义宏的时候,下面的方法才会调用。
#define IsShow
using System.Diagnostics;
namespace _特性
{
internal class Program
{
static void Main(string[] args)
{
ShowMessage("Hi");
}
[Conditional("IsShow")] //使用特性
public static void ShowMessage(string str)
{
Console.WriteLine(str);
}
}
}
3.调用者信息特性 -- 写在函数的参数名返回类型前,参数要赋默认值,调用函数时不用设置这些参数。
[CallerLineNumber] -- 获取该函数被调用时的代码行号
[CallerFilePath] -- 获取被调用函数的路径[CallerMemberName] -- 获取该函数被调用时所在的函数名
class Program
{
static void Main(string[] args)
{
ShowMessage("Hi");
}
public static void ShowMessage(string str,
[CallerLineNumber] int lineNumber = 0,
[CallerFilePath] string filePath = "",
[CallerMemberName] string memberName = "")
{
Console.WriteLine(str);
Console.WriteLine(lineNumber);
Console.WriteLine(filePath);
Console.WriteLine(memberName);
}
}
4. [DebuggerStepThrough] -- 调试的时候会直接跳过下面的方法
5. 自定义特性类
- 类名要以Attribute结尾
- 该类要继承自Attribute类
- 要把该类设置为sealed不可继承
- 要在该类上标注一个特性,用来指定该自定义特性类是作用在哪里的。 如:[AttributeUsage(AttributeTargets.Class)]--作用在类上
namespace _自定义特性类
{
//用来标记一些信息
[AttributeUsage(AttributeTargets.Class)]
internal sealed class InformationAttribute:Attribute
{
public string developer; //开发者
public string version; //版本
public string description; //描述
public InformationAttribute(string developer, string version, string description)
{
this.developer = developer;
this.version = version;
this.description = description;
}
}
}