任何人都可以想到一个更好的方法来做到以下几点:
public string ShortDescription
{
    get { return this.Description.Length <= 25 ? this.Description : this.Description.Substring(0, 25) + "..."; }
}
我本来希望只做string.Substring(0,25),但如果字符串小于提供的长度,它会引发异常.
Mic*_*tum 28
我经常需要这个,我为它写了一个扩展方法:
public static class StringExtensions
{
    public static string SafeSubstring(this string input, int startIndex, int length, string suffix)
    {
        // Todo: Check that startIndex + length does not cause an arithmetic overflow - not that this is likely, but still...
        if (input.Length >= (startIndex + length))
        {
            if (suffix == null) suffix = string.Empty;
            return input.Substring(startIndex, length) + suffix;
        }
        else
        {
            if (input.Length > startIndex)
            {
                return input.Substring(startIndex);
            }
            else
            {
                return string.Empty;
            }
        }
    }
}
如果你只需要它一次,那就是矫枉过正,但如果你经常需要它,它就会派上用场.
编辑:添加了对字符串后缀的支持.传入"...",你可以在较短的字符串上得到你的省略号,或者传入string.Empty,没有特殊的后缀.
Wel*_*bog 23
return this.Description.Substring(0, Math.Min(this.Description.Length, 25));
没有这个...部分.实际上,你的方式可能是最好的.
mar*_*mka 11
public static Take(this string s, int i)
{
    if(s.Length <= i)
        return s
    else
        return s.Substring(0, i) + "..."
}
public string ShortDescription
{
    get { return this.Description.Take(25); }
}
| 归档时间: | 
 | 
| 查看次数: | 2591 次 | 
| 最近记录: |