C#反射的GetCustomAttributes方法

23 篇文章 0 订阅

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

属性规范,如:

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#
[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

M. Knott, version 2.00

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值