c# - C# NullChecking: a is null vs object.Equals(a, null)
问题描述
当前版本的 C#(高于 7.1)有以下两种方法来检查变量是否为空:
// first one
object.Equals(a, null);
// second one
a is null;
我想知道,每种方式的优点是什么。是否有任何特殊情况可以同时使用它们?
解决方案
等于证明身份,这意味着对象完全相同。您可以覆盖 Equals,在这种情况下您可以检查它们的属性。(在 object.Equals 的情况下,您证明身份)。
如果 expr 不为空,则 is 表达式为真,并且以下任何一项为真:(SRC:https ://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is )
expr 是与 type 相同类型的实例。
expr is an instance of a type that derives from type. In other words, the result of expr can be upcast to an instance of type.
expr has a compile-time type that is a base class of type, and expr has a runtime type that is type or is derived from type. The compile-time type of a variable is the variable's type as defined in its declaration. The runtime type of a variable is the type of the instance that is assigned to that variable.
expr is an instance of a type that implements the type interface.
在这里您可以找到如何覆盖 Equals: https ://docs.microsoft.com/de-de/dotnet/api/system.object.equals?view=netframework-4.8
这里有一些例子:
public class Word
{
public string Name;
public Word(string name)
{
Name = name;
}
//Euqals is no overriden
public override bool Equals(object obj)
{
return base.Equals(obj);
}
public class OtherClass
{
public OtherClass()
{
Word word = new Word("word");
Word otherWord = new Word("word");
string a = null;
var r = a == null; //true
var r2 = object.Equals(a, null);//true
var r3 = word.Name is string; //true
var r4 = word.Name is Word; //false
var r5 = word.Equals(otherWord); //false
}
}
如果您在班级中覆盖 equals :
public class Word
{
public string Name;
public Word(string name)
{
Name = name;
}
//Override Equals
public override bool Equals(object obj)
{
if ((obj == null) || !this.GetType().Equals(obj.GetType()))
{
return false;
}
else
{
Word thisWord = (Word) obj;
return (Name == thisWord.Name) /* && (Other properties)*/;
}
}
public class OtherClass
{
public OtherClass()
{
Word word = new Word("word");
Word otherWord = new Word("word");
string a = null;
var r = a == null; //true
var r2 = object.Equals(a, null);//true
var r3 = word.Equals(otherWord); //true
}
}
推荐阅读
- react-native - react-native - 如何将组件中的子级数量限制为只有一个?
- javascript - 打开一个新窗口,然后提交表单
- angular - Angular 组件交互双向绑定方法
- wpf - 使用数据绑定填充数据网格列
- xamarin - Xamarin iOS 模拟器 - 错误“找不到设备”
- c - 使用 Inline/C 从 Perl 调用外部 C 函数(在共享库中)不起作用
- cookies - 大公司的 Cookie 政策
- android - 应用被拒绝。适用于 Android TV 的 Google Play 资格问题
- swift - 迅速。从 Int 获取 Int 的最佳方式?
- visual-studio-code - 如何设置 VSCode 以遵循 Style CI 设置的“规则”?