问题
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