【问题标题】:Index and length must refer to a location in the string c#索引和长度必须引用字符串 c# 中的位置
【发布时间】:2016-03-15 07:27:45
【问题描述】:

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

这是被踢出的代码行:

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

totalMarginMonth 等于 41.3 并且当我收到错误时是十进制类型。我知道字符串的长度不是 5,但大多数值的长度至少为 5。我是否必须在子字符串之前放置一个 if 语句来读取传入的字符串的长度?

【问题讨论】:

  • 什么...将字符串长度截断为 5 的目的是什么?

标签: c# asp.net substring


【解决方案1】:

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

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

【讨论】:

  • 我应该说 totalMarginMonth 是小数,因此你不能在小数上调用长度
  • 没关系,只需调用 ToString() 两次。更新了答案
  • 太棒了!这行得通,我尝试过类似的东西,但我之前没有尝试将它保存到 int
【解决方案2】:

编写一个可以随处使用的扩展方法:

public static class StringExtensions
{
  public static string Truncate( this string s , int maxLength )
  {
    if ( s == null ) throw new ArgumentNullException("s");
    if ( maxLength < 0 ) throw new ArgumentOutOfRangeException("maxLength");

    return s.Length <= maxLength ? s : s.Substring(0,maxLength);
  }
}

那么它是一个简单的问题:

string text = totalMarginMonth.ToString().Truncate(5);

【讨论】:

    【解决方案3】:

    您不能将长度作为子字符串中的第二个值传递吗?

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 2021-08-24
      • 1970-01-01
      相关资源
      最近更新 更多