我想知道为什么给定代码的输出(在LinqPad中执行它)
void Main() {
Compare1((Action)Main).Dump();
Compare2(Main).Dump();
}
bool Compare1(Delegate x) {
return x == (Action)Main;
}
bool Compare2(Action x) {
return x == Main;
}
Run Code Online (Sandbox Code Playgroud)
总是:
False
True
Run Code Online (Sandbox Code Playgroud)
我天真地预计它会出现True在两种情况下.
==委托类型的两个表达式之间的重载解析的准确规则是什么?
请考虑以下代码(using System;需要的地方):
static class ProgramA
{
static void TargetMethod(object obj)
{
}
static void Main()
{
Action<object> instance1 = TargetMethod;
Action<object> instance2 = TargetMethod;
Action<string> a1 = instance1;
Action<Uri> a2 = instance2;
Console.WriteLine((object)a1 == (object)a2);
Console.WriteLine((Delegate)a1 == (Delegate)a2);
Console.WriteLine((Action<object>)a1 == (Action<object>)a2);
Console.WriteLine(a1 == a2); // warning CS0253: Possible unintended reference comparison; to get a value comparison, cast the right hand side to type 'System.Action<string>'
}
}
Run Code Online (Sandbox Code Playgroud)
说明:
instance1并且instance2是同一运行时类型的两个独立实例,泛型Action<in T>是逆变的 …