在C#中将Int转换为Generic Nullable Enum

时间:2014-08-14 02:03:49

标签: c# generics casting enums nullable

我想将一个int值转换为可以为空的枚举使用泛型函数。我认为这很容易,尤其是所有关于enum / int cast的所有SO。我发现的最接近的问题是this one,但不幸的是,它并没有处理可以为空的枚举。 This question解决了Nullable枚举问题,但没有使用泛型。

以下是我尝试做的简单示例:

public enum SouthParkCharacters
{
    Stan = 0,
    Kyle = 1,
    Eric = 2,
    Kenny = 3
}

public static T CastNullableEnum<T>(int value)
{
    return (T)(object)((int?)value).Value;
}


public static T SomeFunction<T>(this int anyEnumValue)
{
        SouthParkCharacters? spc = SouthParkCharacters.Kenny;

        spc = CastNullableEnum<SouthParkCharacters>(3); //I am working!
        spc = CastNullableEnum<SouthParkCharacters?>(3); //Raise error Specified cast is not valid.

        //This function will be public so I won't have control over the T
        T finalValue = CastNullableEnum<T>(anyEnumValue); //Raise error Specified cast is not valid.

        return finalValue;

}

正如你在上一个函数中看到的那样,一个不可为空的枚举的转换正在工作。问题是我希望能够从另一个泛型函数调用CastNullableEnum,它可以使用可以为空的枚举作为泛型类型。

我知道你可以将泛型类型作为可空的泛型CastNullableEnum<T?>传递,但是我们可以反过来(即将可空的底层类型传递给泛型函数)吗?

如果无法做到这一点,那么我想解决方法是找到在CastNullableEnum函数中转换枚举值的正确方法。

3 个答案:

答案 0 :(得分:4)

我可能读错了这个问题,买你可以从可空中获取基础类型并使用Enum.Parse而不是直接投射。

public T CastNullableEnum<T>(int value) 
{
    var enumType = Nullable.GetUnderlyingType(typeof(T));
    if (Enum.IsDefined(enumType, value)) 
    {
        return (T)(object)Enum.Parse(enumType, value.ToString());
    }
    return default(T);
}

var test1 = CastNullableEnum<SouthParkCharacters?>(3); 
//returns Kenny

var test2 = CastNullableEnum<SouthParkCharacters?>(9); 
// returns null

答案 1 :(得分:1)

有趣的问题。这段代码的问题是将整数转换为可以为空的枚举,这是不可能的。

  SouthParkCharacters? enumValue = (SouthParkCharacters?)int.MaxValue;
  if (enumValue.HasValue)
     {
         Console.WriteLine("it still has value");
     }

上面的代码正在运行,它导致enumValue仍然是HasValue。

但无论如何,如果你在编译后看一下C#代码,它将是这样的:

public static T CastNullableEnum<T>(int value)
    {
        Type type = typeof(T);
        return (T)((object)value);
    }
    public static T SomeFunction<T>(int anyEnumValue)
    {
        Program.SouthParkCharacters? spc = new Program.SouthParkCharacters?(Program.SouthParkCharacters.Kenny);
        spc = new Program.SouthParkCharacters?(Program.CastNullableEnum<Program.SouthParkCharacters>(new int?(3)));
        spc = Program.CastNullableEnum<Program.SouthParkCharacters?>(new int?(3));
        return Program.CastNullableEnum<T>(new int?(anyEnumValue));
    }

现在,请注意

spc = new Program.SouthParkCharacters?(Program.CastNullableEnum<Program.SouthParkCharacters>(new int?(3))); 

这就是Unspecified Cast Exception的来源;因为新的SouthParkCharacters?(int value)需要一个Integer。

有趣的是,当你使用Immediate运行时,你不会遇到这个问题。有意思,是吗?

答案 2 :(得分:1)

这将有效:

public static T IntToEnum<T>(object value)
{
    if (value == null)
        return (T)value;

    else if (typeof(T).IsEnum)
        return (T)value;

    else if (Nullable.GetUnderlyingType(typeof(T))?.IsEnum == true)
        return (T)Enum.ToObject(Nullable.GetUnderlyingType(typeof(T)), (int)value);

    throw new Exception(string.Format("Value cannot be converted from {0} to {1}", value.GetType().Name, typeof(T).Name));
}

可用于可空和常规枚举

public enum Codes
{
    A = 1,
    B = 2,
    C = 3
}

static void Main(string[] args)
{
    Console.WriteLine(IntToEnum<Codes?>(1));
    Console.WriteLine(IntToEnum<Codes?>(null));
    Console.WriteLine(IntToEnum<Codes>(2));
}