开发者

c#: Actions incomparable?

开发者 https://www.devze.com 2023-02-20 06:40 出处:网络
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.

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?

Cheers AC


You are doing it wrong.

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");
}

The output is:

== 
True 

Equals 
True 

ReferenceEquals 
True

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");

Then they all report false.

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()
{
}

Then the output is:

== 
True 

Equals 
True 

ReferenceEquals 
False

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


You can compare Method and Target properties.


You can compare action.Method and action.Target.

0

精彩评论

暂无评论...
验证码 换一张
取 消