【问题标题】:Are attributes in C# using reflection? [closed]C# 中的属性是否使用反射? [关闭]
【发布时间】:2013-02-25 10:11:37
【问题描述】:

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

【问题讨论】:

  • 是的........

标签: c# .net custom-attributes


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    是的。假设你有一个对象 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
            }
    

    【讨论】:

    • 如果要检查属性的存在,那么Attribute.IsDefined明显便宜
    • 我同意...如果您需要使用属性属性,请使用我的代码。
    【解决方案3】:

    是的,您使用反射来检查类型或成员是否具有自定义属性。 这是一个获取给定类型的 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 ;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-21
      • 1970-01-01
      • 2020-12-27
      • 1970-01-01
      • 1970-01-01
      • 2017-05-31
      • 1970-01-01
      相关资源
      最近更新 更多