public class SomeAttr: Attribute
{
void Method()
{
//here I want to know the type this instance of attribute is applied to
}
}
最佳答案
在常规 .NET 中,它不会也不能(除非您手动告诉它);对不起。您需要在属性构造函数/属性中包含一些 typeof(Foo)
。如果您在谈论 AOP(PostSharp 等),那么一切都将结束。
如果您指的是 TypeDescriptor
使用的一些属性([DisplayName]
、[TypeConverter]
等),那么可能有其他选项 - 但实现起来相当具体且不简单。
关于c# - 属性的代码如何知道它应用于什么类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1510366/