[英]c#: Actions incomparable?
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.
与==的比较总是返回false,就像Equals-method一样,即使它是同一个实例。
My question is: Is it really not possible or am I doing it wrong? 我的问题是:这真的不可能,还是我做错了?
Cheers AC 干杯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: 如果我相信你,当你说“即使它是同一个实例”时,通过LINQPad执行的以下代码告诉我你一定做错了,或者“同一个实例”是不正确的:
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. 换句话说,
==
, a.Equals(b)
和a.Equals(b)
object.ReferenceEquals(a, b)
表示它是同一个实例。
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. 换句话说,我现在有两个
Action
实例,而不仅仅是一个,但它们仍然相等。
您可以比较Method
和Target
属性。
您可以比较action.Method
和action.Target
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.