String.IsNullOrWhiteSpace() vs is null

huangapple go评论67阅读模式
英文:

String.IsNullOrWhiteSpace() vs is null

问题

我只是想确保在C# 11.0 (.NET 7)中执行这个操作是有意义的:

if (filePath is null || String.IsNullOrWhiteSpace(filePath))
    return false;

我的想法是,IsNull... 使用了'=='运算符,而这个运算符可以被重载,而'is'则不行。

英文:

I just want to be sure that doing this makes sense in C# 11.0 (.NET 7):

if (filePath is null || String.IsNullOrWhiteSpace(filePath))
    return false;

My thought is that IsNull... uses '==' operator, that can be overloaded, while 'is' can not.

答案1

得分: 3

几乎可以肯定您的代码是多余的:如果filePathstring类型,则以下代码足够:

if (string.IsNullOrWhiteSpace(filePath)) {
  ...
}

"几乎"是用于处理filePath类型如下所示的特殊情况的情况:

public class MyPath {
  ...

  public static implicit operator string(MyPath value) {
    ...
  }
}

在这种情况下,您当前的代码双重检查是有意义的:

MyPath filePath = ...

if (filePath is null || string.IsNullOrWhiteSpace(filePath)) {
  ...
}

我们检查filePath是否为null,或者当它不为null时,其string表示是否为null或仅包含空格。

英文:

Almost certainly your code is redundant: if filePath is string then

if (string.IsNullOrWhiteSpace(filePath)) {
  ...
} 

is enough. "Almost" is for exotic case when filePath is of type like this:

public class MyPath {
  ...

  public static implicit operator string(MyPath value) {
    ...
  }
}

In this case your current code with double check makes sense:

MyPath filePath = ...

if (filePath is null || string.IsNullOrWhiteSpace(filePath)) {
  ...
} 

we check if filePath is null or when it's not null its string representation is null or consists of white spaces only.

huangapple
  • 本文由 发表于 2023年2月24日 05:37:13
  • 转载请务必保留本文链接:https://go.coder-hub.com/75550569.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定