如何扩展方法编制?方法

由网友(初吻给了奶嘴)分享简介:如何在C#编译器实现扩展方法?How the C# compiler implement extension methods?推荐答案这个过程是完全一样的重载解析:The process is exactly the same as overload resolution:Func(myObject);编译器...

如何在C#编译器实现扩展方法?

How the C# compiler implement extension methods?

推荐答案

这个过程是完全一样的重载解析:

The process is exactly the same as overload resolution:

Func(myObject);

编译器检查所​​有功能命名为FUNC,并尝试匹配的静态类型myObject的到parametrs(可能需要使用转换,向上转型为基类)。如果成功,然后调用相应的功能。

The compiler checks all functions named "Func" and tries to match the static type of myObject to the parametrs (possibly using conversions, upcasting to base class). If it succeeds, then calls the appropriate function.

如果你意识到你可以以正常方式调用扩展方法,那么它清除了:

If you realize that you can call extensions methods "in a normal way", then it clears up:

static class MyExtensions
{
    public static void MyFunc(this string arg)
    {
        // ...
    }
}

string a = "aa";
MyExtensions.MyFunc(a); // OK
a.MyFunc();             // same as above, but nicer

有关给定类型(在此字符串),编译器只是看起来所有的静态函数的第一个参数这修改和尝试匹配的静态类型上的左边。 (在该示例的a),在该函数的参数类型。

For the given type (here string), the compiler just looks for all static functions with "this" modifier on the first argument and tries to match the static type on the left of the . (in this example "a") with the parameter type in the function.

阅读全文

相关推荐

最新文章