c# - 在没有 try block 的情况下将枚举从对象转换为 long?

标签 c# object enums .net

跟随我的测试源。从枚举对象获取值的好方法是什么?必须长期支持。我正在尝试不使用 try/catch block 。

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;

最佳答案

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

关于c# - 在没有 try block 的情况下将枚举从对象转换为 long?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2064028/

相关文章:

javascript - 如果单击按钮,如何停止执行文本框事件更改方法

javascript - 从此对象中选择特定属性值时遇到问题

javascript - 在 JavaScript 对象中按值查找

c# - c#中的托管指针数组

c# - 将方法参数转换为枚举

c++ - 如何在另一个文件中使用一个 .proto 文件的枚举?

c# - 如何在 WPF 应用程序页面而不是窗口中禁用最大化按钮

c# - 将依赖属性 (View) 与属性 (ViewModel) 同步

c# - 简单快速的异步二进制 TCP 套接字服务器?

ios - 如何拥有类似下面的枚举,但要动态配置而不是静态配置?