英文:
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
几乎可以肯定您的代码是多余的:如果filePath是string类型,则以下代码足够:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论