通过反射得到绑定在类的属性上的特性信息

来源:互联网 发布:java ee课件 编辑:程序博客网 时间:2024/05/21 10:22

标题够绕的 :)

 

using System;
using System.Reflection;
using System.Collections;

 

// 特性类

public class CoTestAttribute : Attribute

    string m_attributeName1;
    

    public string AttributeName1
    {
        get{return m_attributeName1;}
        set{m_attributeName1 = value;}
    }
}

 

// 正常类

public class CoTestClass
{
    string m_classProperty1;


    [CoTest(AttributeName1="attribute value")]
    public string ClassProperty1
    {
        get{return m_classProperty1;}
        set{m_classProperty1 = value;}
    }
}

 

class MainClass
{
    # region 正确结果

 

    // 通过类型
    Type classType1 = typeof(CoTestClass);
    PropertyInfo PI1 = classType1.GetProperty("ClassProperty1");
    object[] resultArray1 = PI1.GetCustomAttributes(typeof(CoTestAttribute), false);
    CoTestAttribute result1 = resultArray1[0] as CoTestAttribute;
    Console.WriteLine("得到正确信息: " + result1.AttributeName1);
    Console.WriteLine();

 

    // 通过实例  
    CoTestClass classInstance1 = new CoTestClass();
    classInstance1.ClassProperty1 = "property value";
    PropertyInfo instancePI = classInstance1.GetType().GetProperty("ClassProperty1");
    object[] resultArray2 = instancePI.GetCustomAttributes(typeof(CoTestAttribute), false);
    CoTestAttribute result2 = resultArray2[0] as CoTestAttribute;
    Console.WriteLine("得到正确信息: " + result2.AttributeName1);
    Console.WriteLine();

 

    # endregion

 

    # region 错误结果

 

    // 通过类型
    Type classType2 = typeof(CoTestClass);
    object[] errorResult1 = classType2.GetCustomAttributes(typeof(CoTestAttribute), false);
    if(errorResult1.Length == 0)
    {
       Console.WriteLine("未得到需要的信息!");
    }
    Console.WriteLine();

 

    // 通过实例  
    CoTestClass classInstance2 = new CoTestClass();
    classInstance2.ClassProperty1 = "property value";
    object[] errorResult2 = classInstance2.GetType().GetCustomAttributes(typeof(CoTestAttribute), false);
    if(errorResult2.Length == 0)
    {
       Console.WriteLine("未得到需要的信息!");
    }

 

    # endregion

 

    Console.ReadLine();

}

原创粉丝点击