.NET Core中的System.Attribute.GetCustomAttribute

编程入门 行业动态 更新时间:2024-10-12 16:23:46
本文介绍了.NET Core中的System.Attribute.GetCustomAttribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试将以下方法(在.NET Framework 4.6.2中可以正常工作)转换为.NET Core 1.1。

I'm trying to convert the following method (which works fine in .NET Framework 4.6.2) to .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; }

此代码给我错误

属性不包含GetCustomAttribute的定义。

Attribute does not contain a definition for GetCustomAttribute.

任何想法。 NET Core是否应等于?

Any idea what the .NET Core equivalent of this should be?

PS我尝试了以下操作,但似乎引发异常。不确定异常是什么,因为它只会一起停止应用程序。我尝试将代码放在 try catch 块中,但它仍然停止运行,因此我无法捕获异常。

P.S. I tried the following but it seems to throw an exception. Not sure what the exception is because it just stops the app all together. I tried putting the code in a try catch block but still it just stops running so I couldn't capture the exception.

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 指令:

If you add a package reference to System.Reflection.Extensions or System.Reflection.TypeExtensions, then MemberInfo gets a lot of extension methods like GetCustomAttribute<T>(), GetCustomAttributes<T>(), GetCustomAttributes(), etc. You use those instead. The extension methods are declared in System.Reflection.CustomAttributeExtensions, so you'll need a using directive of:

using System.Reflection;

在您的情况下, member.GetCustomAttribute< TAttribute>()应该做您需要的一切。

In your case, member.GetCustomAttribute<TAttribute>() should do everything you need.

更多推荐

.NET Core中的System.Attribute.GetCustomAttribute

本文发布于:2023-11-06 08:24:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563184.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Core   NET   System   GetCustomAttribute   Attribute

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!