Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/29.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 索引和长度必须引用字符串c中的位置#_C#_Asp.net_Substring - Fatal编程技术网

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

C# 索引和长度必须引用字符串c中的位置#,c#,asp.net,substring,C#,Asp.net,Substring,我在C#中动态构建一个表,从数据库中提取值,并获取索引和长度必须引用字符串异常中的一个位置 下面是一行被踢出的代码: cl.Text = totalMarginMonth.ToString().Substring(0,5); totalMarginMonth等于41.3,当我得到错误时,它是十进制类型。我知道字符串的长度不是5,但大多数值的长度至少为5。我是否必须在子字符串之前放入if语句来读取传入的字符串的长度?只需将第二个值钳制到子字符串即可 int len = Math.Min(tota

我在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);

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

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

编写一个可在任何地方使用的扩展方法:

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);
  }
}

我应该说明totalMarginMonth是一个十进制数,因此不能对十进制数调用length。这很好,只需调用ToString()两次。更新了答案太棒了!这起作用了,我尝试过类似的东西,但在什么之前我没有尝试过将它保存为int。。。将字符串长度截断为5的目的到底是什么?
string text = totalMarginMonth.ToString().Truncate(5);