如何扩展方法编制? [英] How are extension methods compiled?

查看:156
本文介绍了如何扩展方法编制?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在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.

这篇关于如何扩展方法编制?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆