【发布时间】:2013-05-23 21:38:37
【问题描述】:
在用属性修饰的类型上调用GetCustomAttributes() 后调用属性构造函数。是否可以从构造函数中确定调用类型。我想做类似于以下的事情并且不要抛出。
class Program
{
static void Main(string[] args)
{
var myAttributedClassType = typeof(MyAttributedClass);
var customAttributes = myAttributedClassType.GetCustomAttributes(false)
.OfType<MyAttribute>();
if (customAttributes.Any(x => x.CallingType != myAttributedClassType))
{
throw new Exception("MyAttribute.CallingType was incorrect.");
}
}
}
[AttributeUsage(AttributeTargets.Class)]
class MyAttribute : Attribute
{
public Type CallingType { get; set; }
public MyAttribute()
{
// magic to set CallingType goes here
}
}
[MyAttribute]
class MyAttributedClass { }
更新:
我知道这可以通过构造函数中的命名参数轻松完成
[MyAttribute(CallingType = typeof(MyAttributedClass)
或必填参数
public MyAttributed(Type callingType)
{
CallingType = callingType; // this doesn't qualify as magic ;)
}
但希望有办法避免它,因为类型对象本身(我想要的值)是 GetCustomAttributes 的调用者
【问题讨论】:
-
stackoverflow.com/questions/1235617/… 可以将类型传递给属性构造函数
-
没有好的方法。你也许可以用堆栈跟踪/帧做一些事情,但没有什么漂亮
-
@cheedep 我试图避免传入类型,因为在一个类型上可能有很多这样的情况,它看起来过于多余。
-
@MarcGravell 谢谢,我就是这么想的。
-
你可以用 postsharp 来做(见stackoverflow.com/questions/7851365/…),但它使用一些编译时魔法在幕后做同样的事情。
标签: c# .net reflection attributes