Resharper, ICloneable and never null
本文关键字:never null and ICloneable Resharper | 更新日期: 2023-09-27 18:08:27
Resharper抱怨下面的代码,说最后的空检查是多余的,因为'表达式总是假的':
ICloneable data = item as ICloneable;
if (data == null)
throw new InvalidCastException("blah blah, some error message");
object copy = data.Clone();
if (copy == null) // <-- this is where it complains.
return default(T);
它怎么知道它永远不会为空?
ReSharper假定你的对象遵循ICloneable
的契约,其中规定
生成的克隆必须与原始实例类型相同,或与原始实例兼容。
从data
被检查为非空的事实和假设你从ICloneable.Clone()
的实现返回相同或兼容类型的对象ReSharper得出结论,copy
也是非空的,触发警告。
当然,从Clone
返回null
是绝对可能的。但是,返回null
将是一个编码错误,因此最好跳过null检查。
From MSDN:
实现者须知
iclonable接口只要求Clone方法的实现返回当前对象实例的副本。
如果你满足了合同的要求,Clone
方法不应该返回null
。