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

我正在尝试将以下方法(在.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>()应该做您需要的一切.

相关文章

本文将从上往下,循序渐进的介绍一系列相关.NET的概念,先从...
基于 .NET 的一个全新的、好用的 PHP SDK + Runtime: Pe...
.NET 异步工作原理介绍。
引子 .NET 6 开始初步引入 PGO。PGO 即 Profile Guided Opti...
前言 2021/4/8 .NET 6 Preview 3 发布,这个版本的改进大多来...
前言 开头防杠:.NET 的基础库、语言、运行时团队从来都是相...