自定义属性

突发奇想在.NET上做一个权限控制的东西,想仿SAP权限管理的思想去实现。

第一个要实现的东西在ABAP代码中经常见到的一个。

[authentification (权限对象)]

business logic code

为了实现[authentification ()]就意味着我必须实现一个自定义属性,于是从MSDN上看了几篇文章,嘿嘿。写了下面的一些代码,不做过多解释,只是把代码贴出来。

[System.AttributeUsage(AttributeTargets.All)]
public class AuthAttribute : System.Attribute
{
public string ObjectName;

public AuthAttribute (string name)
{
this.ObjectName = name;
}

public void PrintName()
{
Console.WriteLine("My name is :{0}", ObjectName);
}
}

这个就是自定义属性的那个类,从Attribute类继承。由于主要做到对方法的权限控制,所以Attribute属性应当作用于Method而不是class。(为此稍有头痛)

class Program
{
static void Main(string[] args)
{
AttributeTest t = new AttributeTest();

//MemberInfo m = typeof(AttributeTest);

MethodInfo m = typeof(AttributeTest).GetMethod("print");

//object att = m.GetCustomAttributes(true);

foreach(object att in m.GetCustomAttributes(true))
{
if (att is AuthAttribute)
{
AuthAttribute i = (AuthAttribute)att;

i.PrintName();
}
}

t.print();

Console.Read();
}
}
public class AttributeTest
{
[Auth("Liang-Q")]
public void print()
{

Console.WriteLine("I am Liang-Q");

}
}

至此就算完成了,通过一个反射的机制获取了使用Auth属性的method的自定义属性,并且执行了属性中的一个方法。

嘿嘿,我只是要写一句话,自定义属性类的名字是AuthAttribute,而在使用时候可以把Attribute去掉。

O(∩_∩)O~

[@more@]

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/14820420/viewspace-1016135/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/14820420/viewspace-1016135/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值