为什么没有参数没有IsNullOrEmpty重载方法?

Adr*_*ore 7 c#

当试图弄清楚字符串是空还是空时,我通常已经有了字符串.这就是为什么我希望像String.IsNullOrEmpty()这样的实用函数能够在没有参数的情况下工作:

String myString;
bool test=myString.IsNullOrEmpty();
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用,因为IsNullOrEmpty需要String参数.相反,我必须写:

String myString;
bool test=String.IsNullOrEmpty(myString);
Run Code Online (Sandbox Code Playgroud)

为什么会这样?这似乎不必要地笨重.当然我可以轻松地为此编写自己的扩展方法,但这似乎是一个非常明显的遗漏,所以我想知道是否有任何好的理由.我无法相信微软已经忘记了这个功能的无参数重载.

mqp*_*mqp 27

这种方法已经存在了多久,被添加到C#扩展方法,在此之前扩展方法,有没有办法来定义一个实例方法/属性,例如xyz.IsNullOrEmpty(),你仍然可以调用,如果xyznull.

  • IsNullOrEmpty似乎是最令人愉快地实现的属性,实际上,但遗憾的是我们没有扩展属性. (10认同)

Dan*_*ner 27

如果字符串是null,调用IsNullOrEmpty()将导致NullReferenceException.

 String test = null;

 test.IsNullOrEmpty(); // Instance method causes NullReferenceException
Run Code Online (Sandbox Code Playgroud)

现在我们有扩展方法,我们可以使用扩展方法实现它并避免异常.但总是要记住,这只能起作用,因为扩展方法只不过是静态方法的语法糖.

public static class StringExtension
{
   public static Boolean IsNullOrEmpty(this String text)
   {
      return String.IsNullOrEmpty(text);
   }
}
Run Code Online (Sandbox Code Playgroud)

使用此扩展方法,后续操作永远不会抛出异常

 String test = null;

 test.IsNullOrEmpty(); // Extension method causes no NullReferenceException
Run Code Online (Sandbox Code Playgroud)

因为这只是语法糖.

 StringExtension.IsNullOrEmpty(test);
Run Code Online (Sandbox Code Playgroud)


Ros*_*ant 5

在C#3.0和扩展方法之前,无法在null对象上调用方法.