请解释扩展方法给我 [英] Please explain extension methods to me
问题描述
我只是看着在此张贴:的什么是扩展方法最好或最有趣的使用,你见过?
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.
推荐答案
它们适用于C#和VB。他们可以模拟添加方法不在你的控制之下班
They are available to C# and VB. They allow you to simulate the addition of methods to classes that are not under your control.
您可以,例如,你可以添加的 WORDCOUNT
方法字符串。
You could, for instance, you could add a WordCount
method to string.
因此,而不是
MyStringUtils.WordCount(一些字符串)
您可以只写一些字符串.WordCount()
。
public static class MyExtensions
{
public static int WordCount(this String str)
{
return MyStringUtils.WordCount( str );
}
}
这是严格的语法糖和艾滋病可读性。你基本上创建将在智能感知为目标类型来表示一个静态方法。
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.
这篇关于请解释扩展方法给我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!