如何从自定义属性确定所连接型? [英] How to determine the attached type from within a custom attribute?

查看:110
本文介绍了如何从自定义属性确定所连接型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有可以分配到一个类的自定义属性, [FooAttribute] 。我想这样做,从属性中,为确定哪种类型实际上已经利用了我。例如如果我有:

  [FooAttribute]
公共类酒吧
{
}
 

在$ C $下FooAttribute,我怎么能确定它是加我吧级?我不是专门找了律师的类型,我只是想使用反射来设置的友好名称。例如,

  [FooAttribute(NAME =MyFriendlyNameForThisClass)
公共类酒吧
{
}

公共类FooAttribute()
{
  公共FooAttribute()
  {
    //我如何获得目标类型的名字吗? (作为缺省)
  }
}
 

解决方案

首先,你可能会考虑现有的 [显示名称] 保持友好名称。正如已经覆盖,你根本无法获取属性这里面的信息。你可以看一下,从酒吧的属性,但在一般情况下,从属性做到这一点的唯一方法是通过类型的的属性 - 即

  [美孚(有些名的typeof(酒吧)
 

它究竟是什么,你想干什么?可能还有其他的选择......

请注意,对于国际化,RESX等;你也可以继承 DisplayNameAttribute ,并通过覆盖显示名称吸气提供从键查找。

I have a custom attribute which can be assigned to a class, [FooAttribute]. What I would like to do, from within the attribute, is determine which type has actually used me. e.g. If I have:

[FooAttribute]
public class Bar
{
}

In the code for FooAttribute, how can I determine it was Bar class that added me? I'm not specifically looking for the Bar type, I just want to set a friendly name using reflection. e.g.

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

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

解决方案

First off, you might consider the existing [DisplayName] for keeping friendly names. As has already been covered, you simply can't get this information inside the attribute. You can look up the attribute from Bar, but in general, the only way to do it from the attribute would be to pass the type into the attribute - i.e.

[Foo("Some name", typeof(Bar)]

What exactly is it you want to do? There may be other options...

Note that for i18n, resx, etc; you can subclass DisplayNameAttribute and provide lookup from keys by overriding the DisplayName getter.

这篇关于如何从自定义属性确定所连接型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆