例如在Asp.net MVC Web Application中的,我们想快速了解某个Action上是否有某个Attribute. 那我们可以使用这样的扩展方法:
/// <summary> /// Gets the method. /// </summary> /// <typeparam name="T">Type</typeparam> /// <param name="instance">The instance.</param> /// <param name="methodSelector">The method selector.</param> /// <returns>MethodInfo</returns> public static MethodInfo GetMethod<T>(this T instance, Expression<Func<T, object>> methodSelector) { // it is not work all method return ((MethodCallExpression)methodSelector.Body).Method; } /// <summary> /// Gets the method. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="instance">The instance.</param> /// <param name="methodSelector">The method selector.</param> /// <returns>MethodInfo</returns> public static MethodInfo GetMethod<T>(this T instance, Expression<Action<T>> methodSelector) { return ((MethodCallExpression)methodSelector.Body).Method; } /// <summary> /// Determines whether the specified member has attribute. /// </summary> /// <typeparam name="TAttribute">The type of the attribute.</typeparam> /// <param name="member">The member.</param> /// <returns> /// <c>true</c> if the specified member has attribute; otherwise, <c>false</c>. /// </returns> public static bool HasAttribute<TAttribute>( this MemberInfo member) where TAttribute : Attribute { return GetAttributes<TAttribute>(member).Length > 0; } /// <summary> /// Gets the attributes. /// </summary> /// <typeparam name="TAttribute">The type of the attribute.</typeparam> /// <param name="member">The member.</param> /// <returns></returns> public static TAttribute[] GetAttributes<TAttribute>( this MemberInfo member) where TAttribute : Attribute { var attributes = member.GetCustomAttributes(typeof(TAttribute), true); return (TAttribute[])attributes; }
如何使用,请看下面的代码,我们使用lambda表达式获取某个方法,然后获取其上面的Attribute:
[Fact] public void GetHttpPostAttributeFromCreateAction() { // Arrange var controller = GetEmployeeController(new MemeoryEmployeeBoService()); //Act bool hasPostAttribute =controller.GetMethod(e => e.Create(new Employee())) .HasAttribute<HttpPostAttribute>(); // Assert Assert.True(hasPostAttribute); }
希望对您开发有帮助。
您可能感兴趣的文章:
用扩展方法来为Enum类型加入业务逻辑
用扩展方法来扩展IDataReader接口
为IEnumerable<T>增加Combine的扩展方法
用扩展方法生成分割符字符串
Orderby的扩展方法
作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog。
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
· 如何使用 Uni-app 实现视频聊天(源码,支持安卓、iOS)