C# 方法声明中的this关键字是什么意思?

C# 方法声明中的this关键字是什么意思?,c#,.net,methods,C#,.net,Methods,我发现一个声明如下的方法: public static int WordCount(this string str) { return str.Length; } arg.WordCount(); Class.WordCount(arg); 在这个特定的上下文中,这个关键字是什么?它使它成为一种扩展方法 这意味着您可以这样调用该方法: public static int WordCount(this string str) { return str.Length; } a

我发现一个声明如下的方法:

public static int WordCount(this string str)
{
    return str.Length;
}
arg.WordCount();
Class.WordCount(arg);

在这个特定的上下文中,
这个
关键字是什么?

它使它成为一种扩展方法

这意味着您可以这样调用该方法:

public static int WordCount(this string str)
{
    return str.Length;
}
arg.WordCount();
Class.WordCount(arg);
而不是像这样:

public static int WordCount(this string str)
{
    return str.Length;
}
arg.WordCount();
Class.WordCount(arg);
它主要用于扩展不能直接修改其源代码的类型(因此得名)。

它是一个。扩展方法允许您扩展类型。这对于像
string
这样的类型非常有用,因为您无法访问这些类型的源代码

使用您提供的示例,而不是调用

string test = "foo";
var result = StaticClass.WordCount(test);
您可以按如下方式使用它:

string test = "foo";
var result = test.WordCount();

琐事:LINQ是使用扩展方法实现的,事实上这是将扩展方法添加到.NET framework的主要原因。

这一定是重复的。@BrianRasmussen。标题并转到第一个链接