C#:动作无与伦比? [英] c#: Actions incomparable?

查看:100
本文介绍了C#:动作无与伦比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试比较两个动作.与==的比较总是返回false,与Equals方法一样,即使它是同一实例也是如此.

I'm trying to compare two Actions. The comparison with == always returns false as does the Equals-method even though it's the same instance.

我的问题是:真的不可能吗或者我做错了吗?

My question is: Is it really not possible or am I doing it wrong?

欢呼AC

推荐答案

您做错了.

如果我相信您,当您说即使是同一实例"时,下面的代码将通过 LINQPad 告诉我您必须做错了什么,否则同一个实例"是不正确的:

If I am to believe you, when you say "even though it's the same instance", then the following code executed through LINQPad tells me that you must be doing something wrong, or the "same instance" is incorrect:

void Main()
{
    Action a = () => Debug.WriteLine("test");
    Action b = a;

    (a == b).Dump("==");
    (a.Equals(b)).Dump("Equals");
    object.ReferenceEquals(a, b).Dump("ReferenceEquals");
}

输出为:

== 
True 

Equals 
True 

ReferenceEquals 
True

换句话说, == a.Equals(b) object.ReferenceEquals(a,b)都表示其同一实例.

In other words, both ==, a.Equals(b) and object.ReferenceEquals(a, b) says its the same instance.

另一方面,如果我重复代码:

On the other hand, if I duplicate the code:

Action a = () => Debug.WriteLine("test");
Action b = () => Debug.WriteLine("test");

然后他们都报告为假.

如果我将它们都链接到一个命名方法,而不是一个匿名方法:

If I link them both to a named method, and not an anonymous one:

void Main()
{
    Action a = Test;
    Action b = Test;

    (a == b).Dump("==");
    (a.Equals(b)).Dump("Equals");
    object.ReferenceEquals(a, b).Dump("ReferenceEquals");
}

private static void Test()
{
}

然后输出为:

== 
True 

Equals 
True 

ReferenceEquals 
False

换句话说,我现在有两个 Action 实例,不仅是一个,而且它们仍然相等.

In other words, I now got two Action instances, not just one, but they still compare equal.

这篇关于C#:动作无与伦比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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