在C#中将int与System.Numerics.BigInteger进行相互转换 [英] converting int to/from System.Numerics.BigInteger in C#
问题描述
我有一个返回 System.Numerics.BigInteger
的属性。当我将该属性转换为int时,出现此错误。
I have a property that returns System.Numerics.BigInteger
. When I casting the property to int, I got this error.
无法将类型'System.Numerics.BigInteger'转换为'int'
如何在C#中与 System.Numerics.BigInteger
相互转换?
How can I convert int to/from System.Numerics.BigInteger
in C#?
推荐答案
从BigInteger转换为Int32 是明确的,因此仅将 BigInteger
变量/属性分配给 int
变量是行不通的:
The conversion from BigInteger to Int32 is explicit, so just assigning a BigInteger
variable/property to an int
variable doesn't work:
BigInteger big = ...
int result = big; // compiler error:
// "Cannot implicitly convert type
// 'System.Numerics.BigInteger' to 'int'.
// An explicit conversion exists (are you
// missing a cast?)"
此方法有效(尽管如果在运行时可能会引发异常,该值太大而无法容纳在 int
变量中):
This works (although it might throw an exception at runtime if the value is too large to fit in the int
variable):
BigInteger big = ...
int result = (int)big; // works
请注意,如果 BigInteger
值装在对象
中,您无法对其拆箱并将其转换为 int
同时:
Note that, if the BigInteger
value is boxed in an object
, you cannot unbox it and convert it to int
at the same time:
BigInteger original = ...;
object obj = original; // box value
int result = (int)obj; // runtime error
// "Specified cast is not valid."
这有效:
BigInteger original = ...;
object obj = original; // box value
BigInteger big = (BigInteger)obj; // unbox value
int result = (int)big; // works
这篇关于在C#中将int与System.Numerics.BigInteger进行相互转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!