如何从自定义属性确定所连接型?自定义、属性

由网友(知善)分享简介:我有可以分配到一个类的自定义属性, [FooAttribute] 。我想这样做,从属性中,为确定哪种类型实际上已经利用了我。例如如果我有:[FooAttribute]公共类酒吧{}在$ C $下FooAttribute,我怎么能确定它是加我吧级?我不是专门找了律师的类型,我只是想使用反射来设置的友好名称。例如,[...

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

  [FooAttribute]
公共类酒吧
{
}
 

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

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

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

解决方案

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

  [美孚(有些名的typeof(酒吧)
 
MATLAB 基础知识 数据类型 表 向表和时间表中添加自定义属性

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

请注意,对于国际化,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.

阅读全文

相关推荐

最新文章