如果没有检索自定义属性的信息和对其进行操作的方法,则定义自定义属性并将其放置在源代码中就没有意义。C# 具有一个反射系统,可用来检索用自定义属性定义的信息。主要方法是 GetCustomAttributes,它返回对象数组,这些对象在运行时等效于源代码属性。此方法具有多个重载版本。有关更多信息,请参见 Attribute。

C#反射――属性规范

C#

[Author("H. Ackerman", version = 1.1)]  



class SampleClass 

在概念上等效于:

C#

Author anonymousAuthorObject = new Author("H. Ackerman");  


anonymousAuthorObject.version = 1.1; 

但是,直到查询 SampleClass 以获取属性时才会执行此代码。对 SampleClass 调用 GetCustomAttributes 会导致按上述方式构造并初始化一个 Author 对象。如果类还有其他属性,则其他属性对象的以类似方式构造。然后 GetCustomAttributes 返回 Author 对象和数组中的任何其他属性对象。之后就可以对此数组进行迭代,确定根据每个数组元素的类型所应用的属性,并从属性对象中提取信息。

C#反射――示例

下面是一个完整的示例。定义一个自定义属性,将其应用于若干实体并通过反射进行检索。

C#

[System.AttributeUsage(System.AttributeTargets.Class |  


                       System.AttributeTargets.Struct,  



                       AllowMultiple = true)  // multiuse attribute  



]  



public class Author : System.Attribute  



{  



    string name;  




    public double version;  



 



    public Author(string name)  



    {  



        this.name = name;  




        version = 1.0;  // Default value  



    }  


 



    public string GetName()  



    {  



        return name;  



    }  


}  


 



[Author("H. Ackerman")]  




private class FirstClass  



{  



    // ...  



}  


 



// No Author attribute  




private class SecondClass  



{  



    // ...  



}  


 



[Author("H. Ackerman"), Author("M. Knott", version = 2.0)]  




private class ThirdClass  



{  



    // ...  



}  


 



class TestAuthorAttribute  



{  



    static void Main()  



    {  



        PrintAuthorInfo(typeof(FirstClass));  




        PrintAuthorInfo(typeof(SecondClass));  




        PrintAuthorInfo(typeof(ThirdClass));  



    }  


 



    private static void PrintAuthorInfo(System.Type t)  



    {  



        System.Console.WriteLine("Author information for {0}", t);  




        System.Attribute[] attrs = System.Attribute.GetCustomAttributes(t);  // reflection  



 



        foreach (System.Attribute attr in attrs)  



        {  



            if (attr is Author)  



            {  


                Author a = (Author)attr;  



                System.Console.WriteLine("   {0}, version {1:f}", a.GetName(), a.version);  



            }  


        }  


    }  


} 

输出

Author information for FirstClass

H. Ackerman, version 1.00

Author information for SecondClass

Author information for ThirdClass

H. Ackerman, version 1.00