gpt4 book ai didi

c# - 索引和长度必须引用字符串中的位置 c#

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:50 27 4
gpt4 key购买 nike

我正在用 C# 动态构建一个表,我正在从数据库中提取值,我正在获取索引和长度必须引用字符串异常中的位置。

这是被踢出的代码行:

cl.Text = totalMarginMonth.ToString().Substring(0,5);

totalMarginMonth等于41.3,报错时是小数类型。我知道字符串的长度不是 5,但大多数值的长度至少为 5。在对它进行子字符串化之前,我是否必须放置一个 if 语句来读取传入的字符串的长度?

最佳答案

只需将第二个值限制为子字符串即可。

int len = Math.Min(totalMarginMonth.ToString().Length, 5);
c1.Text = totalMarginMonth.ToString().Substring(0, len);

关于c# - 索引和长度必须引用字符串中的位置 c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34188717/

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