安全地截断C#中可能为"null"的字符串

Sam*_*tar 0 c#

我有以下方法但如果字符串为null则失败.如果字符串为null,我怎么能让它返回null?

public static string Truncate(this string value, int maxChars)
{
    return value.Length <= maxChars ?
           value :
           value.Substring(0, maxChars) + " ..";
}
Run Code Online (Sandbox Code Playgroud)

有人也可以向我解释"这个"的用途.对不起,我不太擅长C#,这不是我的代码.

Jon*_*eet 10

通过检查null并正确返回:)

public static string Truncate(this string value, int maxChars)
{
    if (value == null)
    {
        return null;
    }
    return value.Length <= maxChars ?
           value : value.Substring(0, maxChars) + " ..";
}
Run Code Online (Sandbox Code Playgroud)

或者你甚至可以使用另一个条件:

public static string Truncate(this string value, int maxChars)
{
    return value == null ? null
        : value.Length <= maxChars ? value 
        : value.Substring(0, maxChars) + " ..";
}
Run Code Online (Sandbox Code Playgroud)