【问题标题】:Access the declaring class in a custom attribute?访问自定义属性中的声明类?
【发布时间】:2015-02-19 15:04:26
【问题描述】:

我创建了一个自定义属性,我想在其中访问自定义属性属性的声明类。

例如:

public class Dec
{
    [MyCustomAttribute]
    public string Bar {get;set;}
}

在这里,我想(在 MyCustomAttribute 的 cass 中)获取声明类的类型(Dec)。 这有可能吗?

编辑:感谢大家的回复。我今天学到了一些新东西。

【问题讨论】:

  • 你知道属性只有在你请求的时候才会被实例化,对吧?参见例如:stackoverflow.com/questions/12196647/…,所以当你实例化它们时,你清楚地知道父类的类型(因为你必须这样做type.GetCustomAttributes()

标签: c# reflection annotations


【解决方案1】:

正如我所写的,属性只有在您使用type.GetCustomAttributes() 请求它们时才会被实例化,但那时您已经拥有Type。你唯一能做的就是:

[AttributeUsage(AttributeTargets.Property)]
public class MyCustomAttribute : Attribute 
{
    public void DoSomething(Type t) 
    {

    }
}

public class Dec 
{
    [MyCustomAttribute]
    public string Bar { get; set; }
}

// Start of usage example

Type type = typeof(Dec);
var attributes = type.GetCustomAttributes(true);
var myCustomAttributes = attributes.OfType<MyCustomAttribute>();
// Shorter (no need for the first var attributes line): 
// var myCustomAttributes = Attribute.GetCustomAttributes(type, typeof(MyCustomAttribute), true);


foreach (MyCustomAttribute attr in myCustomAttributes) 
{
    attr.DoSomething(type);
}

所以将类型作为参数传递。

【讨论】:

  • 小记,但Attribute.GetCustomAttributes(type,typeof(MyCustomAttribute),true) 将避免需要通过OfType&lt;&gt; 过滤
  • 谢谢 - 我采用了这种方法。
【解决方案2】:

这也可能有效:

class MyCustomAttribute : Attribute
{
    public Type DeclaringType { get; set; }
}

public class Dec
{
    [MyCustomAttribute(DeclaringType=typeof(Dec))]
    public string Bar { get; set; } 
}

【讨论】:

    【解决方案3】:

    不,不是——除了 PostSharp、Roslyn 等构建时工具。

    您需要找到一种不同的方法——也许将Type 作为构造函数参数传入;或(更有可能),但无论您想要基于属性的任何逻辑,请注意声明上下文;即假设 MyCustomAttribute 有一个 Foo() 方法,使其成为 Foo(Type declaringType) 或类似的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-25
      • 1970-01-01
      • 2020-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-20
      相关资源
      最近更新 更多