C#中的属性是否使用反射

本文关键字:反射 是否 属性 | 更新日期: 2023-09-27 18:00:51

我想知道C#中的属性是如何工作的。我知道如何声明属性或如何创建属性。我想知道如何在特定属性上生成特定行为。我应该使用反射吗?

C#中的属性是否使用反射

除非您使用诸如PostSharp之类的AOP框架,否则很少有属性可以直接影响您的代码,它们只是一些内置属性。不能将行为添加到自定义属性中。因此:是的,您必须使用反射来测试自定义属性的存在,和/或物化属性(只检查存在比物化它们更便宜(。

如果你正在做这些工作,你可能需要考虑缓存通过属性获得的信息,这样你就不需要每次需要元数据时都使用反射。

是。假设你有一个对象o,并且你想检查你的属性是否存在。你所要做的就是:

Type t = o.GetType();
        object[] attributes = t.GetCustomAttributes(typeof(MyCustomAttribute));
        if (attributes.Length>0){
            MyCustomAttribute a = attributes[0] as MyCustomAttribute;
            //use your attribute properties to customize your logic
        }

是的,您可以使用反射来检查类型或成员是否具有自定义属性。下面是一个获取给定类型的MyCustomAttribute实例的示例。它将返回第一个MyCustomAttribute声明或null(如果未找到(:

private static MyCustomAttribute LookupMyAttribute(Type type)
{
    object[] customAttributes = type.GetCustomAttributes(typeof(MyCustomAttribute), true);
    if ((customAttributes == null) || (customAttributes.Length <= 0))
        return null;
    return customAttributes[0] as MyCustomAttribute ;
}