将enum从object转换为long而不使用try块?

时间:2010-01-14 12:34:23

标签: c# object enums .net

按照我的测试来源进行操作。从枚举对象获取值的好方法是什么?必须支持多久。我正在尝试没有try / catch块。

enum ELong: long { a = 0x100000000 };
enum ENormal { a = 25 }

        var l = (object) ELong.a;
        var n = (object)ENormal.a;
        //will cast into the correct size
        int ii = (int)n; //ok
        long ll = (long)l; //ok
        //wont cast if its too big
        ll = (long)n; //cast exception
        //or too small
        n = (int)l; //cast exception//compile error. Cannot cast
        //lets try preventing the exception with is
        if (n is int)
            ii = (int)n;//doesnt get here.
        if (n is long)
            ll = (long)n;//doesnt get here.
        if (l is int)
            ii = (int)l;//doesnt get here
        if (l is long)
            ll = (long)l;//doesnt get here
        //WHY!!!!
        //Maybe as will do the trick?
        if (n as int? != null)
            ii = (int)n;//doesnt get here.
        if (n as long? != null)
            ll = (long)n;//doesnt get here.
        if (l as int? != null)
            ii = (int)l;//doesnt get here
        if (l as long? != null)
            ll = (long)l;//doesnt get here
        //geez. What is more stange is (int) will work while (int?) will not
        int? ni = (int?)n;//cast exception
        int iii = (int)n; //works
        ll = (long)n;

3 个答案:

答案 0 :(得分:6)

long test1 = Convert.ToInt64(l); // 4294967296
long test2 = Convert.ToInt64(n); // 25

答案 1 :(得分:5)

<强>解释

if (n is int)
        ii = (int)n;//doesnt get here.
    if (n is long)
        ll = (long)n;//doesnt get here.
    if (l is int)
        ii = (int)l;//doesnt get here
    if (l is long)
        ll = (long)l;//doesnt get here

n l 既不是 int / long 也不是 long?/ int?,它们属于类型你的枚举,所以这是预期的行为。

<强>解决方案

可能你应该使用转换类来实现你想要的目标。

答案 2 :(得分:3)

来自MSDN的示例:

static object GetAsUnderlyingType(Enum enval)
{
    Type entype = enval.GetType();

    Type undertype = Enum.GetUnderlyingType(entype);

    return Convert.ChangeType( enval, undertype );
}
  1. 转换为基础类型(int或long)
  2. 将转换后的值转换为您的变量(我想简单地将结果分配给长变量)。