在可移植库中将字符串转换为枚举
本文关键字:转换 枚举 字符串 可移植 | 更新日期: 2023-09-27 18:36:48
我正在尝试在可移植类库中以通用方式将字符串转换为枚举
Targes 是:.NET 4.5、Windows 8、Windows Phone 8.1、Windows Phone Silverlight 8
我有这个字符串扩展,我以前在Winform应用程序中使用过。但是在这个库中它不编译。行if (!typeof(TEnum).IsEnum)
public static class StringExtensions
{
public static TEnum? AsEnum<TEnum>(this string value) where TEnum : struct, IComparable, IFormattable
{
if (!typeof(TEnum).IsEnum)
throw new ArgumentException("TEnum must be an enumerated type");
TEnum result;
if (Enum.TryParse(value, true, out result))
return result;
return null;
}
}
所以我的问题是:在给定的上下文中,我如何测试给定类型是枚举?
如果不支持Type.IsEnum
,您可以随时使用:
if (typeof(TEnum).BaseType != typeof(Enum))
(当然,前提是BaseType
可用。
你可以尝试使用GetTypeInfo
:
using System.Reflection; // to get the extension method for GetTypeInfo()
if(typeof(TEnum).GetTypeInfo().IsEnum)
// whatever