加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – .NET Core中的System.Attribute.GetCustomAttribute

发布时间:2020-12-15 17:42:55 所属栏目:百科 来源:网络整理
导读:我正在尝试将以下方法(在.NET Framework 4.6.2中正常工作)转换为.NET Core 1.1. public static TAttribute GetCustomAttributeTAttribute(MemberInfo member) where TAttribute : Attribute{ var attr = System.Attribute.GetCustomAttribute(member,typeof(
我正在尝试将以下方法(在.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>()应该做您需要的一切.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读