问个关于Attribute的问题

bluery 2010-06-14 11:54:42
我定义了一个Attribute类:
[AttributeUsage(AttributeTargets.All)]
public class BlueryAttribute : Attribute
{
private string privilege;

public BlueryAttribute(string str)
{
this.privilege = str;
}

public string Privilege
{
get
{
return this.privilege;
}
}
}

在页面代码的类和方法使用:
[BlueryAttribute("A")]
public partial class AttributeTest : PageBase
{

protected void Page_Load(object sender, EventArgs e)
{

}

[BlueryAttribute("B")]
protected void Button1_Click(object sender, EventArgs e)
{

}
}

其中,PageBase是页面的基类,我需要在里面的某事件(不一定是OnLoad)完成以下工作:如果是回发,则可以获取到标识在方法上特性字符串(“B”)
PageBase类如下:
public class PageBase : System.Web.UI.Page
{
public PageBase() { }

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
BlueryAttribute attribute = (BlueryAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(BlueryAttribute));
}
}

我的问题:不知道如何获取相应方法上的特性,请指教,谢谢~
...全文
121 8 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
皇城龙三 2010-06-14
  • 打赏
  • 举报
回复
attribute.Privilege就应该是“A”吧:

(BlueryAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(BlueryAttribute));
捷哥1999 2010-06-14
  • 打赏
  • 举报
回复
那你就在子类中对属性赋值,在子类的对应事件中获取。
bluery 2010-06-14
  • 打赏
  • 举报
回复
嗯~那么我可以在不知道方法名的前提下,获取到它的字符串吗?因为可能是很多页面继承PageBase,每个方法名都不一样~

谢谢各位~
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 bluery 的回复:]
但实际上这个时候获得的attribute.Privilege是“A”
不知道问题出在哪里。。
[/Quote]

因为你是在AttributeTest类型上查询的。你要查询“方法上特性字符串”,那么你就去针对代表这个方法的MethodInfo执行GetCustomAttribute,而不是针对页面的Type。
捷哥1999 2010-06-14
  • 打赏
  • 举报
回复
你是不是创建该属性是,就是用A!?
bluery 2010-06-14
  • 打赏
  • 举报
回复
但实际上这个时候获得的attribute.Privilege是“A”
不知道问题出在哪里。。
hitlcyu19 2010-06-14
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 computerfox 的回复:]

获取你得到的特性的Privilege属性即可!
BlueryAttribute attribute = (BlueryAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(BlueryAttribute));
attribute.Privilege
[/Quote]
Up
捷哥1999 2010-06-14
  • 打赏
  • 举报
回复
获取你得到的特性的Privilege属性即可!
BlueryAttribute attribute = (BlueryAttribute)Attribute.GetCustomAttribute(this.GetType(), typeof(BlueryAttribute));
attribute.Privilege

111,098

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • AIGC Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧