隐式方法组转换的疑难杂症 [英] Implicit method group conversion gotcha

查看:113
本文介绍了隐式方法组转换的疑难杂症的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么给定的代码(在LinqPad执行它)

I am wondering why the output of the given code (execute it in LinqPad)

void Main() {
    Compare1((Action)Main).Dump();
    Compare2(Main).Dump();
}

bool Compare1(Delegate x) {
    return x == (Action)Main;
}

bool Compare2(Action x) {
    return x == Main;
}



永远是:

is always:

 False
 True

我天真地期望它是在这两种情况下。

I have naively expected it to be True in both cases.

推荐答案

这是怎么回事当编译为IL,然后反编译回C#的样子。请注意,在这两种情况下有新动作(主) - 一个新的参考对象(代表)与指针存放在里面实际的方法。

This is how it looks when compiled to IL and then decompiled back to C#. Note that in both cases there's new Action(Main) - a new reference object (delegate) with pointer to actual method stored inside.

private static void Main()
{
    Program.Compare1(new Action(Program.Main)).Dump();
    Program.Compare2(new Action(Program.Main)).Dump();
    Console.ReadLine();
}

private static bool Compare1(Delegate x)
{
   return x == new Action(Program.Main);
}

private static bool Compare2(Action x)
{
   return x == new Action(Program.Main);
}

如果接下来我们就一起来看看到CIL,前者使用 CEQ (参考比较),而后者使用通话布尔[mscorlib程序] System.Delegate :: op_Equality(类[mscorlib程序] System.Delegate,类[mscorlib程序]系统。代表)比较代表。

If then we take a look into CIL, the former uses ceq (reference comparison) and the latter uses call bool [mscorlib]System.Delegate::op_Equality(class [mscorlib]System.Delegate, class [mscorlib]System.Delegate) to compare delegates.

首先返回,因为包装的委托行为是两个不同的参考对象。

First returns false because actions wrapping your delegates are two distinct reference objects.

第二个返回真正作为对代表类实现平等运算符比较内包装的实际目标(操作)。

Second returns true as the equality operator implemented on the Delegate class compares actual targets inside wrappers (actions).

这篇关于隐式方法组转换的疑难杂症的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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