System.Attribute.GetCustomAttribute 在 .NET 核心中
System.Attribute.GetCustomAttribute in .NET Core
我正在尝试将以下方法(在 .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 应该是什么吗?
P.S。我尝试了以下但它似乎抛出异常。不确定异常是什么,因为它只是一起停止了应用程序。我尝试将代码放在 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>()
应该可以满足您的所有需求。
您需要使用GetCustomAttribute
方法:
using System.Reflection;
...
typeof(<class name>).GetTypeInfo()
.GetProperty(<property name>).GetCustomAttribute<YourAttribute>();
如在 .Net Framework Core official GitHub
页面上找到的那样,使用以下
type.GetTypeInfo().GetCustomAttributes()
我正在尝试将以下方法(在 .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 应该是什么吗?
P.S。我尝试了以下但它似乎抛出异常。不确定异常是什么,因为它只是一起停止了应用程序。我尝试将代码放在 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>()
应该可以满足您的所有需求。
您需要使用GetCustomAttribute
方法:
using System.Reflection;
...
typeof(<class name>).GetTypeInfo()
.GetProperty(<property name>).GetCustomAttribute<YourAttribute>();
如在 .Net Framework Core official GitHub
页面上找到的那样,使用以下
type.GetTypeInfo().GetCustomAttributes()