在可移植库中将字符串转换为枚举

Convert String To Enum in a portable lib

我正在尝试以通用方式在便携式 class 库中将字符串转换为枚举

目标是:.NET 4.5、Windows8、WindowsPhone8.1、WindowsPhoneSilverlight 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