在方法属性不起作用 [英] Attribute on method doesn't work
本文介绍了在方法属性不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个属性(在C#库)的方法。问题是,当我打电话给我的方法,属性不叫。我不明白为什么!
I have a method with an attribute (in c# library). The problem is that attribute is not call when I call my method. I don't understand why !
我的code:
[AttributeUsage(System.AttributeTargets.Method)]
public class RequireAuthorization : System.Attribute
{
private bool _protected = true;
public RequireAuthorization(bool protect)
{
_protected = protect;
}
}
public class MyClass(){
[RequireAuthorization(true)]
public bool method1(){
// some actions
}
}
一些想法吗?
推荐答案
属性仅仅是元数据,它们是即时编译和你的codeBase类的一部分,但他们并不需要运行。
Attributes are just metadata, they are jitted and part of your codebase, but they don't need to run.
要强制运行你的自定义属性,你可以使用反射,下面会引起你的 RequireAuthorization
类的构造函数来执行:
To enforce running your custom Attribute you could use reflection, the following would cause the constructor of your RequireAuthorization
class to be executed:
MemberInfo memberInfo = typeof(MyClass).GetMethod("method1");
var attributes = memberInfo.GetCustomAttributes(false);
这篇关于在方法属性不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文