在c#中,如果对象为 null 时直接调用 trim() 方法,会抛出 nullreferenceexception。为了避免程序崩溃,必须在调用前使用条件判断、空合并运算符或模式匹配来确保对象不为空。

如何安全地处理可能为空的字符串?
最安全的做法是使用 C# 8.0 引入的模式匹配语法 is not null,或者使用三元运算符结合 string.IsNullOrEmpty。这样可以避免在 null 值上执行方法调用。

using System;
public class Program
{
public static void Main()
{
string input = null;
// 方式一:使用 is not null (C# 8.0+)
if (input is not null)
{
Console.WriteLine(input.Trim());
}
else
{
Console.WriteLine("Input is null");
}
// 方式二:使用三元运算符
string result = input != null ? input.Trim() : "";
Console.WriteLine(result);
}
}
Trim() 对不同类型的输入有何影响?
当输入是包含空白字符的字符串时,Trim() 会移除首尾的空白。如果输入是空字符串 "",Trim() 返回空字符串。只有当输入为 null 时才会引发异常。

using System;
public class Program
{
public static void Main()
{
string s1 = " hello ";
string s2 = "";
string s3 = null;
Console.WriteLine(s1.Trim()); // 输出: hello
Console.WriteLine(s2.Trim()); // 输出: (空行)
try
{
Console.WriteLine(s3.Trim()); // 抛出 NullReferenceException
}
catch (NullReferenceException ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
使用 null-conditional 运算符是否足够?
使用 ?. 运算符可以防止 null 异常,但如果对象为 null,整个表达式将返回 null。这可能导致后续代码接收到意外的 null 值,因此建议结合 ?? 提供默认值。
using System;
public class Program
{
public static void Main()
{
string input = null;
// 使用 null-conditional 和 null-coalescing
string safeTrim = input?.Trim() ?? "default";
Console.WriteLine(safeTrim); // 输出: default
}
}


















