我遇到过几个像下面这样的c#代码实例:

public static int Foo(this MyClass arg)

我还没有找到这个关键字在这种情况下意味着什么解释。见解吗?


当前回答

除了Preet Sangha的解释之外: 智能感知以蓝色箭头显示扩展方法(例如在"Aggregate<>"前面):

你需要一个

using the.namespace.of.the.static.class.with.the.extension.methods;

如果扩展方法与使用它们的代码在不同的名称空间中,则扩展方法将出现并可用。

其他回答

"this"扩展了参数列表中的下一个类

因此在下面的方法签名中,“this”扩展了“String”。Line作为方法的常规参数传递给函数。 SplitCsvLine(此字符串行)

在上面的例子中,“this”类扩展了内置的“String”类。

如果您可以整洁地弹出List<>,即不仅删除第一个元素,而且还返回它,这不是很方便吗?

List<int> myList = new List<int>(1, 2, 3, 4, 5);

没有扩展方法:

public static class ContainerHelper
{
    public static T PopList<T>(List<T> list)
    {
        T currentFirst = list[0];
        list.RemoveAt(0);
        return currentFirst;
    }
}

调用此方法:

int poppedItem = ContainerHelper.PopList(myList);

使用扩展方法:

public static class ContainerHelper
{
    public static T PopList<T>(this List<T> list)//Note the addition of 'this'
    {
        T currentFirst = list[0];
        list.RemoveAt(0);
        return currentFirst;
    }
}

调用此方法:

int poppedItem = myList.PopList();

它们是扩展方法。欢迎来到一个全新的流畅世界。:)

前几天我自己也学过这个:this关键字定义了该方法是继承它的类的扩展。对于你的例子,MyClass将有一个新的扩展方法Foo(它不接受任何参数并返回int;它可以像任何其他公共方法一样使用)。

除了Preet Sangha的解释之外: 智能感知以蓝色箭头显示扩展方法(例如在"Aggregate<>"前面):

你需要一个

using the.namespace.of.the.static.class.with.the.extension.methods;

如果扩展方法与使用它们的代码在不同的名称空间中,则扩展方法将出现并可用。