使用attribute的例子
来源:互联网 发布:scival数据库 编辑:程序博客网 时间:2024/04/26 22:54
转自百度知道的一个回答点击打开链接,第一个专业回答是典型例子,作为参考是不错的,提问者采纳的更好:
假设你的F()方法是定义在下面这个类里面: public class MyClass { [IStudent(Name = "abc", Age = 20)] public void F() { } }那么可以这么去取值: Type type = typeof(MyClass); MethodInfo methodInfo = type.GetMethod("F"); if (methodInfo.IsDefined(typeof(IStudentAttribute), false)) { object[] attributes = methodInfo.GetCustomAttributes(typeof(IStudentAttribute), false); IStudentAttribute studentAttr = (IStudentAttribute)attributes[0]; Console.WriteLine(studentAttr.Name + studentAttr.Age); }实际上,Attribute可以有很多用处,比如说,你可以在某个方法上做标记看有没有权限调用,或者在某个属性上标记,看要如何校验。例如(实在习惯用var关键字了,下面的代码都用var了,还有Linq):假设我们有这么一个标记来说明操作的权限: /// <summary> /// 声明权限的标记 /// </summary> [AttributeUsage(AttributeTargets.Method)] public class PermissonAttribute : Attribute { public string Role { get; set; } public PermissonAttribute(string role) { this.Role = role; } public PermissonAttribute() { } }有一个操作类应用了该标记: /// <summary> /// 文件操作类 /// </summary> public class FileOperations { /// <summary> /// 任何人都可以调用Read /// </summary> [Permisson("Anyone")] public void Read() { } /// <summary> /// 只有文件所有者才能Write /// </summary> [Permisson("Owner")] public void Write() { } } 然后我们写一个工具类来检查操作权限 /// <summary> /// 调用操作的工具类 /// </summary> public static class OperationInvoker { public static void Invoke(object target, string role, string operationName, object[] parameters) { var targetType = target.GetType(); var methodInfo = targetType.GetMethod(operationName); if (methodInfo.IsDefined(typeof(PermissonAttribute), false)) { // 读取出所有权限相关的标记 var permissons = methodInfo .GetCustomAttributes(typeof(PermissonAttribute), false) .OfType<PermissonAttribute>(); // 如果其中有满足的权限 if (permissons.Any(p => p.Role == role)) { methodInfo.Invoke(target, parameters); } else { throw new Exception(string.Format("角色{0}没有访问操作{1}的权限!", role, operationName)); } } } }最后,在使用的时候:var role = "Anyone";var opertion = new FileOperations();// 可以正常调用ReadOperationInvoker.Invoke(operation, "Read", null);// 但是不能调用WriteOperationInvoker.Invoke(operation, "Write", null);
0 0
- 使用attribute的例子
- GNU C attribute section的一个使用例子
- GNU C attribute section的一个使用例子
- C# attribute属性的例子
- Attribute:特性的一个例子
- Attribute 类介绍,例子:对枚举的字段添加Attribute
- 自定义Attribute的使用
- C#Attribute的使用
- C#Attribute的使用(一)
- 特性的简单使用(Attribute)
- 使用weka的select attribute
- Unity Attribute的使用总结
- Unity Attribute的使用总结
- Unity Attribute的使用总结
- Unity Attribute的使用总结
- Unity-内置Attribute的使用
- Attribute与Property 的翻译区别 Attribute的使用范围
- 自定义Attribute例子!
- DB2 在线分析处理(OLAP函数的使用)
- swift学习记录(函数--输入输出参数)
- Git Reference---Branching and Merging(2)
- 局域网部署Docker--从无到有创建自己的Docker私有仓库
- Java将数据库数据导入EXCEL
- 使用attribute的例子
- 对象的深复制和浅复制
- 【Lua C交互】3 - lua调用C模块
- 函数调用过程栈帧变化详解
- 苹果App Store最新应用审核标准
- 如何在Myeclipse,Eclipse中输入一个字母或符号时出现提示各种方法和关键字
- 基本排序_冒泡排序_Java实现
- Java之多线程内存可见性_3(synchronized和volatile比较)
- python编程非常有用的网站