C#特性(Attribute)示例

[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 | 引用: 0 | 查看次数: 4459
发表评论
登录后再发表评论!