我看到以下代码,
public override bool Equals(object obj) { // From the book http://www.amazon.co.uk/Pro-2010-NET-4-0-Platform/dp/1430225491 // Page 254! if (obj is Person && obj != null) ... }
基于我的理解,我认为代码应该重写如下:
public override bool Equals(object obj) { if (obj is Person) ... }
那是对的吗?
基于http://msdn.microsoft.com/en-us/library/scekt9xw%28v=vs.80%29.aspx
如果提供的表达式为非空,则表达式计算结果为true,并且可以将提供的对象转换为提供的类型,而不会引发异常.
我认为没有必要额外检查null.换句话说,该代码“obj!= null”根本不应该被打.
谢谢
// 更新 //
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication2 { class Employee { public static void CheckIsEmployee(object obj) { if (obj is Employee) { Console.WriteLine("this is an employee"); } else if (obj == null) { Console.WriteLine("this is null"); } else { Console.WriteLine("this is Not an employee"); } } } class NotEmployee { } class Program { static void Main(string[] args) { Employee e = new Employee(); Employee.CheckIsEmployee(e); Employee f = null; Employee.CheckIsEmployee(f); NotEmployee g = new NotEmployee(); Employee.CheckIsEmployee(g); } } }
输出结果:
this is an employee this is null this is Not an employee
解决方法
我的偏好是使用as关键字.
public override bool Equals(object obj) { var objectToCompare = obj as Person; if ( objectToCompare == null ) return false; ... }
优点在于,在该方法的后面,您有一个类型化的实例(objectToCompare)来进行比较.
在您的评估中,您是正确的,如果obj不是从Person派生的,或者obj为null,那么Person将返回false,因此obj是Person&&& obj!= null是多余的;你只需要obj就是Person,如果你使用那种风格.从技术上讲,首先检查空值可能会导致性能提升,但增益可以忽略不计.