Attribute的一些用法
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp32
{
class MyCustomAttribute : Attribute
{
public string info;
public MyCustomAttribute(string info)
{
this.info = info;
}
public void TestFun()
{
Console.WriteLine("特性的方法");
}
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct, AllowMultiple = true, Inherited = true)]
public class MyCustom2Attribute : Attribute
{
}
class TestClass
{
[Obsolete("OldSpeak方法已经过时了,请使用Speak方法",false)]
public void OldSpeak(string str)
{
Console.WriteLine(str);
}
public void Speak()
{
}
public void SpeakCaller(string str,[CallerFilePath]string fileName=" ",[CallerLineNumber]int line=0,[CallerMemberName]string target="")
{
}
}
[MyCustom("这个是我自己写的一个类")]
class MyClass
{
[MyCustom("这是一个成员变量")]
public int value;
[MyCustom("这是一个用于计算假发的函数")]
public void TestFun([MyCustom("函数参数")]int a)
{
Console.WriteLine();
}
}
class Program
{
static void Fun()
{
Console.WriteLine("Fun执行");
}
static void Main(string[] args)
{
// MyClass mc = new MyClass();
// Type t = mc.GetType();
// if(t.IsDefined(typeof(MyCustomAttribute),false))
// {
// Console.WriteLine("该类型应用了MyCustom特性");
// }
//object[] array= t.GetCustomAttributes(true);
// for(int i=0;i<array.Length;i++)
// {
// if(array[i] is MyCustomAttribute)
// {
// Console.WriteLine((array[i] as MyCustomAttribute).info);
// (array[i] as MyCustomAttribute).TestFun();
// }
// }
}
}
}