我有一个可以分配给一个类的自定义属性,[FooAttribute]
。我想做的是,从属性内部确定哪种类型实际使用了我。例如如果我有:
[FooAttribute]
public class Bar
{
}
在 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)
}
}
首先,您可能会考虑现有的[DisplayName]
用于保留友好的名称。正如已经介绍过的,您根本无法在属性内获取此信息。您可以从 Bar 查找属性,但一般来说,从属性执行此操作的唯一方法是传递类型into属性 - 即
[Foo("Some name", typeof(Bar)]
你到底想做什么?可能还有其他选择...
请注意,对于 i18n、resx 等;你可以子类化DisplayNameAttribute
并通过覆盖提供从键的查找DisplayName
getter.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)