如何从自定义属性中确定附加类型?

Mar*_*ram 5 .net c# reflection custom-attributes

我有一个可以分配给类的自定义属性[FooAttribute].我想在属性中做的是确定哪种类型实际使用了我.如果我有:

[FooAttribute]
public class Bar
{
}
Run Code Online (Sandbox Code Playgroud)

在FooAttribute的代码中,我如何确定添加了我的Bar类?我不是专门寻找Bar类型,我只是想用反射设置一个友好的名字.例如

[FooAttribute(Name="MyFriendlyNameForThisClass")]
public class Bar
{
}

public class FooAttribute()
{
  public FooAttribute()
  {
    // How do I get the target types name? (as a default)
  }
}
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 5

首先,您可能会考虑[DisplayName]保留友好名称.正如已经涵盖的那样,您根本无法在属性中获取此信息.你可以看一下从酒吧属性,但总的来说,从属性做到这一点的唯一方法是将类型传递进入属性-即

[Foo("Some name", typeof(Bar)]
Run Code Online (Sandbox Code Playgroud)

你究竟想做什么?可能还有其他选择......

注意,对于i18n,resx等; 你可以DisplayNameAttribute通过覆盖DisplayNamegetter 来子类并提供键的查找.