为什么以下代码有效?
呼叫:
SomeObject sO = null;
bool test = sO.TestNull();
Run Code Online (Sandbox Code Playgroud)
码:
public static bool TestNull(this SomeObject sO)
{
return sO == null;
}
Run Code Online (Sandbox Code Playgroud)
这是允许工作还是只是一个错误?
public static IFoo Bar<T>(this IFoo target, ...)
{
// I'm curious about how useful this check is.
if (target == null) throw new ArgumentNullException("target");
...
}
Run Code Online (Sandbox Code Playgroud)
(1)上面的代码对我来说似乎很奇怪,因为我觉得在任何情况下调用代码都是检查它的人.这个领域的扩展方法是否有些微妙适用?
(2)是否存在利用目标可以为空的事实的合法模式?我想这是因为想知道为什么在空引用上调用扩展方法不会像在null引用上调用实例方法那样生成运行时异常.