将数值upanddown值转换为整数变量

本文关键字:整数 变量 upanddown 转换 | 更新日期: 2023-09-27 18:07:33

我在尝试将numericUpAndDown转换为int时遇到了问题。这是我目前掌握的代码。private int counter = numericUpAndDown1.Value;所有的帮助是感激的,谢谢!

将数值upanddown值转换为整数变量

numericUpAndDown1.Valuedecimal类型,因此您不能直接将其存储到INT,需要显式强制转换

private int counter = (int)numericUpAndDown1.Value;

不知道numericUpAndDown1的类型。值属性是,你可以用int来完成。解析为快速&肮脏的解决方案:

private int counter = int.Parse(numericUpAndDown1.Value.ToString());

正如Rahul的回答所建议的,您也可以在numericUpAndDown1的情况下尝试直接强制转换。Value是另一种数字类型。但是,当源值超出整数值的可接受范围(小于/大于2,147,483,647)时,这可能导致运行时异常。

private int counter = (int)numericUpAndDown1.Value;

由于这两种方法都可能抛出异常,因此可以使用int类型。

private int counter = 0;
int.TryParse(numericUpAndDown1.Value.ToString(), out counter);

如果你可以发布更多的代码来提供一些上下文,那么可能有一个更好的建议。

编辑:

下面的应用程序演示了在这种情况下从decimal直接转换为int会抛出异常:

using System;
namespace DecimalToIntTest {
    class Program {
        static void Main(string[] args) {
            decimal x = 3000000000;
            int y = (int)x;
            Console.WriteLine(y);
            Console.Read();
        }
    }
}