namespace Con_Attribute { /// <summary> /// "Sports" 是给构造函数的赋值, Level = 5 是给属性的赋值。 /// </summary> [HobbyAttribute("Sports", Level = 5)] class Student { public string profession; public string Profession { get { return profession; } set { profession = value; } } } class HobbyAttribute : System.Attribute { //兴趣类型 private string type; public string Type { get { return type; } set { type = value; } } //兴趣指数 private int level; public int Level { get { return level; } set { level = value; } } /// <summary> /// 构造函数 /// </summary> /// <remarks>参数值为null的string 危险,所以必需在构造函数中赋值</remarks> /// <param name="_type"></param> public HobbyAttribute(string _type) { this.Type = _type; } } }
下面我们来调用一下看看效果:
class Program { static void Main(string[] args) { #region demo2 //通过反射得到Student类的信息 System.Reflection.MemberInfo info = typeof(Student); HobbyAttribute hobbyatt = (HobbyAttribute)Attribute.GetCustomAttribute(info, typeof(HobbyAttribute)); if (hobbyatt != null) { Console.WriteLine("类名:{0}", info.Name); Console.WriteLine("兴趣类型:{0}", hobbyatt.Type); Console.WriteLine("兴趣指数:{0}", hobbyatt.Level.ToString()); Console.Read(); } #endregion } }
运行结果如下:
或许我们能做些事情,比如页面权限控制。通过Attribute得到该页面.cs类的信息,然后去数据库里面的权限部分匹配,嗯,只是一个思路吧,回头再看看其它效果。
//属性测试 //[TestAttribute(ccvalue="hello")] public class AATest : UIButton { public AATest () { } } //[AttributeUsage(AttributeTargets.Method|AttributeTargets.Class)] [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)] //TestAttribute类仅作用在方法上 public class TestAttribute : Attribute { public string Role{ get; set;} public TestAttribute(string role) { this.Role = role; } public TestAttribute() { } } public class SysDataManager { public SysDataManager() { } [TestAttribute("anyone")] public void ShowInfo() { Utils.Tools.Alert ("anyone:ShowInfo()"); } [TestAttribute("admin")] public void Out2Excel() { Utils.Tools.Alert ("admin:Out2Excel()"); } public void DeleteInfo() { Utils.Tools.Alert ("DeleteInfo()"); } } public static class OperationInvoker { public static void Invoke(object target, string role, string operationName, object[] param) { var methordinfo = target.GetType ().GetMethod (operationName); //获取所有方法 if (methordinfo.IsDefined (typeof(TestAttribute), false)) { var permissons = methordinfo.GetCustomAttributes (typeof(TestAttribute), false).OfType<TestAttribute> (); if (permissons.Any (x => x.Role == role)) { methordinfo.Invoke (target, param); } else { //Console.WriteLine (string.Format ("{0}", role, operationName)); Utils.Tools.Alert (string.Format ("角色{0}没有访问操作{1}的权限!", role, operationName)); //throw new Exception (string.Format ("角色{0}没有访问操作{1}的权限!", role, operationName)); } } } //... }