Problem with Substring() - ArgumentOutOfRangeException

后端 未结 11 1727
抹茶落季
抹茶落季 2020-12-20 11:29

I have a repeater that displays data from my Projects table. There are projectId, name and description. I use Substring(1, 240) on description. But sometimes the string is s

11条回答
  •  情歌与酒
    2020-12-20 12:25

    Based on Jon Skeet's answer, I think it should be checking for null or else it's not exactly a safe method :)

    public static string SafeSubstring(this string text, int start, int length)
    {
        if (text == null) return null;      
    
        return text.Length <= start ? ""
            : text.Length - start <= length ? text.Substring(start)
            : text.Substring(start, length);
    }
    

提交回复
热议问题