将扩展方法传递给期望委托的方法。这个怎么用?
问题描述:
所以在工作中,我使用了一个我们没有写的API,其中一个方法接受了一个委托。出于某种原因,这个想法在我看来,我有一个符合该签名的扩展方法,所以我想知道它是否会起作用。我确信它不会让我惊讶,它确实如此。请允许我以证明:将扩展方法传递给期望委托的方法。这个怎么用?
说我有这些类:
public interface IMyInterface
{
}
public class MyClass : IMyInterface
{
}
public static class Extensions
{
public static string FuncMethod(this IMyInterface imy, int x)
{
return x.ToString();
}
}
现在让我们说我有一个方法签名的地方,看起来像这样:
private static void Method(Func<int, string> func)
{
}
现在我的扩展方法(看起来像它)匹配的签名,但我们都知道,扩展方法只是烟雾和镜子,所以它真的不符合该签名。然而,我可以安全地做到这一点:
var instance = new MyClass();
Method(instance.FuncMethod);
我的问题是,这是如何工作的?编译器为我做出什么让这可以接受。扩展方法的实际签名需要IMyInterface
的实例,但Func
不适用于幕后的情况。
答
实例方法实现为隐藏this
参数。
当您使用扩展方法创建实例委托时,隐藏的this
参数作为第一个常规参数传递给该方法。
答
我不确切知道编译器在做什么来允许这些场景,但期望似乎是合理的。也许这个代码示例将有助于解决这个概念。
MyClass instance = new MyClass();
Func<int, string> f1 = instance.FuncMethod;
Func<int, string> f2 = (i) => instance.FuncMethod(i);
Func<int, string> f3 = (i) => Extensions.FuncMethod(instance, i);