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

标签 c# reflection .net-core system.reflection

我正在尝试将以下方法(在 .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 block 中,但它仍然只是停止运行,所以我无法捕获异常。

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>()应该做你需要的一切。

关于c# - .NET Core 中的 System.Attribute.GetCustomAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43247759/

相关文章:

c# - WPF - 将文本框的内容绑定(bind)到其他文本框

.net - 解析程序集合格名称?

c# - 更新后无法构建 .NET Core 项目

c# - 如果结构具有 ReadOnlySpan 字段,如何将 ref struct 参数传递给 MethodInfo

asp.net-core - 区分大小写的路由

azure - 如何在 Net Core HostBuilder 上配置 Application Insights 采样?

c# - 如何使 ServiceStack 与现有的 MVC/Service/Repository 模式一起工作

java - 需要支持和阻力算法或帮助查找包 com.perseus.analysis

c# - 如何更改特定控件的 Windows 窗体应用程序中的输入语言?

java - 使用 java.lang.Class<T> 实例初始化(加载)java 类