简体   繁体   English

如何正确地从 long 转换为 int?

[英]How to cast correctly from long to int?

I have such method我有这样的方法

        public int foo()
        {
            return (int) MainJsonValues[JsonKeys.DP_PORT.Value];
        }

This method should make cast and return this value此方法应进行强制转换并返回此值

There is how I call this method我是如何调用这个方法的

myObj.foo()

So, it is very strange because as we can see value contains in Dictionary所以,这很奇怪,因为我们可以看到值包含在Dictionary

You can see my debug on screenshot您可以在屏幕截图上看到我的调试

在此处输入图片说明

So, as far as I see this method can't convert from long to int ...所以,据我所知,这个方法不能从long转换为int ...

Error错误

在此处输入图片说明

What am I doing wrong?我究竟做错了什么?

A boxed value type may only be unboxed to the unboxed type or the nullable unboxed type .装箱值类型只能拆箱为拆箱类型可为空的拆箱类型 That is, if you have a boxed long, you may unbox it to long or long?也就是说,如果你有一个盒装的long,你可以把它拆箱成long还是long? , but not any other type. ,但不是任何其他类型。 (See the comments for details.) (详情见评论。)

Therefore you need to do the conversion in two steps:因此,您需要分两步进行转换:

object x = 1L; // boxed long
long y = (long)x; // unboxed
int z = (int)y;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM