我创建了这个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
}
Run Code Online (Sandbox Code Playgroud)
jas*_*son 24
我的注释永远不会因某些原因而被调用?
这是对属性的误解.有效地存在属性以将元数据添加到代码的某些部分(类,属性,字段,方法,参数等).编译器获取属性中的信息并将其烘焙到IL中,当它完成吃源时它会吐出码.
除非有人使用属性,否则属性本身不会做任何事情.也就是说,某人必须在某个时刻发现您的属性,然后对其采取行动.他们坐在你的集会的IL中,但除非有人发现并对他们采取行动,否则他们不做任何事情.只有当他们这样做时才会实例化属性的实例.执行此操作的典型方法是使用反射.
要在运行时获取属性,您必须说出类似的内容
var attributes = typeof(Foo)
.GetMethod("Window_Loaded")
.GetCustomAttributes(typeof(AuthenticationRequired), true)
.Cast<AuthenticationRequired>();
foreach(var attribute in attributes) {
Console.WriteLine(attribute.ToString());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20736 次 |
| 最近记录: |