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

2 .net c# enums object

跟随我的测试源.从枚举对象中获取值的好方法是什么?必须支持多久.我正在尝试没有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;
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 6

long test1 = Convert.ToInt64(l); // 4294967296
long test2 = Convert.ToInt64(n); // 25
Run Code Online (Sandbox Code Playgroud)


Res*_*uta 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
Run Code Online (Sandbox Code Playgroud)

nl既不是int/long也不是long?/ int?,它们是你的枚举类型,所以这是预期的行为.

可能你应该使用Convert类来实现你想要的.