我正在尝试将以下方法(在.NET Framework 4.6.2中正常工作)转换为.NET Core 1.1.
public static TAttribute GetCustomAttribute<TAttribute>(MemberInfo member) where TAttribute : Attribute { var attr = System.Attribute.GetCustomAttribute(member,typeof(TAttribute)); if (attr is TAttribute) return attr; else return null; }
这段代码给了我错误
Attribute does not contain a definition for GetCustomAttribute.
知道.NET Core相当于什么吗?
附:我尝试了以下但似乎抛出异常.不确定异常是什么,因为它只是一起停止应用程序.我尝试将代码放在try catch块中,但它仍然停止运行,所以我无法捕获异常.
public static TAttribute GetCustomAttribute<TAttribute>(MemberInfo member) where TAttribute : Attribute { var attr = GetCustomAttribute<TAttribute>(member); if (attr is TAttribute) return attr; else return null; }
解决方法
如果您向System.Reflection.Extensions或System.Reflection.TypeExtensions添加包引用,则MemberInfo会获取许多扩展方法,如GetCustomAttribute< T>(),GetCustomAttributes< T>(),GetCustomAttributes()等.您使用那些而不是.扩展方法在System.Reflection.CustomAttributeExtensions中声明,因此您需要一个using指令:
using System.Reflection;
在您的情况下,member.GetCustomAttribute< TAttribute>()应该做您需要的一切.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。