[AttributeUsage(AttributeTargets.All,Inherited=false)]
public class TestAttribute : System.Attribute
{
//Fields
private string _description;
//Properties
public string Description
{
get { return _description; }
}
//Constructor
public TestAttribute(string description)
{
this._description = description;
}
}
[Test("user-defined class")]
public class TestClass
{
//Constructor
public TestClass()
{}
//Methods
[Test("user-defined method")]
public int Add(int a, int b)
{
return a + b;
}
}调用示例:
using System;
using System.Reflection;
namespace Console_Application
{
class Program
{
public static void Main(string[] args)
{
Type t = typeof(TestClass);
MemberInfo memberInfo = t;
TestAttribute attribute = (TestAttribute)Attribute.GetCustomAttribute(memberInfo,typeof(TestAttribute));
Console.WriteLine(attribute.Description);
MethodInfo methodInfo = t.GetMethod("Add");
TestAttribute attribute2 = (TestAttribute)Attribute.GetCustomAttribute(methodInfo,typeof(TestAttribute));
Console.WriteLine(attribute2.Description);
Console.ReadKey(true);
}
}
}
评论(0)
暂无评论。