c#: Actions incomparable?

帅比萌擦擦* 提交于 2021-02-20 10:26:43

问题


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


回答1:


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.




回答2:


You can compare Method and Target properties.




回答3:


You can compare action.Method and action.Target.



来源:https://stackoverflow.com/questions/5470607/c-actions-incomparable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!