突发奇想在.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/