请向我解释扩展方法
I just looked at this posting: What is the best or most interesting use of Extension Methods you’ve seen?
I've never heard of extension methods. Do they apply to every language?
What is the point of them? In that particular posting I did not understand the example.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,它们并不适用于所有语言。它们是特定于语言的功能,由 C# 和 Visual Basic 提供(其他语言可能已采用它们,我不知道)。
它们的目的是提供一种方便的语法来调用类或接口上的实用方法。在 C# 2 中,将通过静态类调用实用程序方法,以正常方式传递参数:
使用扩展方法,可以使用看起来像正常成员方法语法的内容更方便地编写:
即使 Count() 不是
IEnumerable
接口的成员。因此,扩展方法可以让您看起来将成员添加到您无法控制的类或接口中。No, they do not apply to every language. They are a language-specific feature, offered by C# and Visual Basic (other languages may have adopted them since, I don't know).
The point of them is to provide a convenient syntax for calling utility methods on a class or interface. In C# 2, a utility method would be called through a static class, passing the argument in the normal way:
With extension methods, this can be written more conveniently using something that looks like normal member method syntax:
even though Count() is not a member of the
IEnumerable<string>
interface. So extension methods let you appear to add members to classes or interfaces that you don't control.它们可用于 C# 和 VB。它们允许您模拟向不受您控制的类添加方法。
例如,您可以添加
WordCount
方法来字符串。而不是
MyStringUtils.WordCount( "some string" )
因此,您可以只编写
"some string".WordCount()
,。这严格来说是“语法糖”,有助于提高可读性。您实质上是在创建一个静态方法,该方法将显示在目标类型的 IntelliSense 中。
They are available to C# and VB. They allow you to simulate the addition of methods to classes that are not under your control.
You could, for instance, you could add a
WordCount
method to string.So instead of
MyStringUtils.WordCount( "some string" )
You could just write
"some string".WordCount()
.This is strictly "syntactic sugar" and aids in readability. You're essentially creating a static method that will be shown in the IntelliSense for the target type.
不,但有些语言具有相同的功能,尽管不一定具有相同的名称。我知道的是 Objective-C 和 Groovy,其中该功能称为“类别”。
No, but some languages have the same feature, though not necessarily under the same name. Those I know about are Objective-C and Groovy, where the feature is called "Categories".