创建一个自定义特性:
// 描述如何使用一个自定义特性 SomethingAttribute
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
//********自定义特性SomethingAttribute**************//
public class SomethingAttribute : Attribute {
private string name; // 名字
private string data; // 日期
public string Name {
get { return name; }
set { name = value; }
}
public string Data {
get { return data; }
set { data = value; }
}
public SomethingAttribute(string name) {
this.name = name;
this.name = name;
}
}
实例化定义
[Something("Amy", Data = "2018-06-18")]
[Something("Jack", Data = "2018-06-18")]
class Test{}
获取自定义特性的中的变量
Type t = typeof(Test);
var something = t.GetCustomAttributes(typeof(SomethingAttribute),true);
foreach(SomethingAttribute each in something)
{
Console.WriteLine("Name:{0}", each.Name);
Console.WriteLine("Data:{0}",each.Data);
}
Conditional的应用
#define BUG
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Threading;
using System.Diagnostics;
namespace helloworld
{
public class Myclass
{
[Conditional("BUG")]
public static void M1(string msg)
{
Console.WriteLine(msg);
}
[Conditional("deBUG")]
public static void M2(string msg)
{
Console.WriteLine(msg);
}
[Conditional("BUG")]
public static void M3(string msg)
{
Console.WriteLine(msg);
}
[Conditional("kk")]
public static void M4(string msg)
{
Console.WriteLine(msg);
}
}
class Program
{
static void Main(string[] args)
{
Myclass.M1("456");
Myclass.M2("845");
Myclass.M3("dadasd");
Myclass.M4("456xcvc");
Console.WriteLine("Main thread ID is:" );
Console.ReadKey();
}
}
}
将头部的#define BUG就会运行M1和M3,定义为#define kk就将会只运行M4方法。
但是注意如果没有写[]的都会执行,所以一般加[]attrible时候,常常看见如果有加一般每个方法上面都会加。