为什么允许空对象上的扩展方法?
允许在空对象上调用扩展方法有什么意义? 这使我不必要地检查扩展方法中的空对象。 AFAIK,我无法理解这一点? 请解释一下。
what is the point of allowing invocation of extension methods on null objects?
this is making me unnecessarily check for a null object in the extension method.
AFAIK,i can't understand this?
Please explain.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
扩展方法是 C# 语言的语法糖,它们被编译为 ILCode 中的普通静态方法调用。静态方法在编译时不知道任何有关参数的信息。
Extension methods are syntactic sugar of the C# language, they get compiled to normal static method calls in ILCode. A static method doesn't know anything about the parameters at compile time.
简而言之,为什么不呢?
如果您在扩展中调用的第一个方法也会抛出正确的错误,有时您可以跳过测试。
您本质上要求代码有所不同,以便:
这似乎对其他用途造成了很大的影响,只是为了节省一行:
Simply put, why not?
You can sometimes skip the test if the first method you call within the extension would also throw the correct error.
You're essentially asking for the code to be different so that:
This seems a lot of an imposition on other uses just to save the one line of:
扩展方法只是语法糖。实际上它们是另一个类上的静态方法,所以既然你可以写
你也可以写
Extension methods are just syntactic sugar. In reality they are static methods on another class, so since you can write
You can also write
有时,允许在 null 对象上调用扩展方法可以简化代码,因为您可以将 null 检查移至方法中而不是调用站点。例如,您可能有一个返回
List
的扩展方法,但如果在 null 对象上调用,则会返回空的List
。Sometimes, allowing the extension method to be called on a null object simplifies your code by allowing you to move the null check into the method instead at the call site. For example, you may have an extension method that returns a
List<T>
, but if called on a null object, returns an emptyList<T>
.NullArgumentException
could take execution time and the user may want to assert instead or use something else.扩展方法只是静态方法:
相当于:
Extension methods are just static methods:
Is equivalent to:
另一个美丽的例子,否则是不可能的:
所以你可以使用
而不是
Another beautiful example that wouldn't be possible otherwise:
So you can use
Instead of