能接收。c#字符串判空扩展方法(如 isnullorwhitespace)的参数可以接收 null,因为扩展方法的第一个参数使用 this 修饰,编译器在调用时会将实例作为实参传入,即使实例为 null,方法内部也能通过判断 obj == null 安全处理,不会抛出 nullreferenceexception。

IsNullOrEmpty 对 null 的处理逻辑是什么
IsNullOrEmpty 方法会直接检查传入的字符串引用是否为 null 或长度为零。如果为 null,它返回 true;如果为空字符串 "",它也返回 true。该方法不涉及任何属性访问,因此对 null 是安全的。

using System;
public class Program
{
public static void Main()
{
string nullStr = null;
string emptyStr = "";
// 测试 IsNullOrEmpty
Console.WriteLine(string.IsNullOrEmpty(nullStr)); // True
Console.WriteLine(string.IsNullOrEmpty(emptyStr)); // True
// 测试扩展方法(假设自定义)
Console.WriteLine(nullStr.IsNullOrWhitespace()); // False (因为不是空白,是null)
Console.WriteLine(" ".IsNullOrWhitespace()); // True
}
}
public static class StringExtensions
{
public static bool IsNullOrWhitespace(this string str)
{
if (str == null) return false; // 注意:这里只判null,不判空白
return string.IsNullOrWhiteSpace(str);
}
}
IsNullOrWhiteSpace 与 IsNullOrEmpty 的区别在哪里
IsNullOrWhiteSpace 在检查 null 和空字符串的基础上,还检查字符串是否仅包含空白字符(如空格、制表符、换行符)。如果字符串全是空白,它返回 true。而 IsNullOrEmpty 不检查空白字符,只关心是否为 null 或 ""。

using System;
public class Program
{
public static void Main()
{
string spaceStr = " ";
// 测试 IsNullOrWhiteSpace
Console.WriteLine(string.IsNullOrWhiteSpace(spaceStr)); // True
// 测试 IsNullOrEmpty
Console.WriteLine(string.IsNullOrEmpty(spaceStr)); // False
}
}
当输入为 null 时,自定义扩展方法如何避免异常
在自定义扩展方法中,必须显式检查 this 参数是否为 null。由于扩展方法是静态方法,this 只是普通参数,不会自动进行空值检查。如果在方法体内直接访问 this.Length 或 this.Trim(),当 this 为 null 时会抛出 NullReferenceException。因此,第一步必须是 if (str == null) return ...;。











