我创建了这个Annotation类
这个例子可能没有意义,因为它总是会抛出异常,但我仍然在使用它,因为我只是试图解释我的问题是什么。由于某些原因,我的注解从未被调用过,有什么解决方案吗?
public class AuthenticationRequired : System.Attribute
{
public AuthenticationRequired()
{
// My break point never gets hit why?
throw new Exception("Throw this to see if annotation works or not");
}
}
[AuthenticationRequired]
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// My break point get here
}发布于 2011-07-25 11:09:29
由于某些原因,
我的注解永远不会被调用,有什么解决方案吗?
这是对属性的一种误解。属性可以有效地将元数据添加到代码的某些部分(类、属性、字段、方法、参数等)。编译器获取属性中的信息,并将其烘焙到IL中,当它完成对源代码的处理时,它会输出IL。
属性本身不会做任何事情,除非有人使用它们。也就是说,在某些情况下,必须有人发现您的属性,然后对其采取行动。它们位于您的程序集的IL中,但它们不会做任何事情,除非有人发现它们并对它们采取行动。只有当他们这样做时,属性的一个实例才会被实例化。这样做的典型方法是使用反射。
要在运行时获得属性,您必须这样说
var attributes = typeof(Foo)
.GetMethod("Window_Loaded")
.GetCustomAttributes(typeof(AuthenticationRequired), true)
.Cast<AuthenticationRequired>();
foreach(var attribute in attributes) {
Console.WriteLine(attribute.ToString());
}https://stackoverflow.com/questions/6811448
复制相似问题