gpt4 book ai didi

c# - 字符串不转换为整数

转载 作者:太空宇宙 更新时间:2023-11-03 11:01:59 25 4
gpt4 key购买 nike

我正在尝试将对象属性的 string 转换为 integer,但我遇到了很多问题。

第一种方法

public class test
{
public string Class { get; set; }
}

//test.Class value is 150.0
var i = Convert.ToInt32(test.Class);

提示Input String is not in a correct format

第二种方法

int i = 0;
Int32.TryParse(test.Class, out i);

上述代码的值始终为零

第三种方法

int j = 0;
Int32.TryParse(test.Class, NumberStyles.Number, null, out j);

这里我得到的值是 150 正确但是因为我使用 null 作为 IFormatProvider 这会有什么问题吗?

在这些情况下,将字符串转换为整数的正确方法是什么?

最佳答案

值 150.0 包含小数分隔符“.”所以不能转换直接转换为任何整数类型(例如 Int32)。您可以获得两阶段转换中的期望值:首先是 double,然后是 Int32

Double d;

if (Double.TryParse(test.Class, NumberStyles.Any, CultureInfo.InvariantCulture, out d)) {
Int32 i = (Int32) d;
// <- Do something with i
}
else {
// <- test.Class is of incorrect format
}

关于c# - 字符串不转换为整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17357951/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com