为什么LINQ的First()需要显式强制转换,而foreach却不需要?

Moh*_*iba 3 c#

有人可以解释一下这段代码如何工作吗?

Action a = action;

Delegate[] alist = a.GetInvocationList();

// conversion between System.Delagate and System.Action is done
foreach(Action ac in alist) {
}

// cannot convert from System.Delagate to System.Action
Delegate firstDelegate = alist.First();
Action firstAction = firstDelegate; // compile error needs explicit cast
Run Code Online (Sandbox Code Playgroud)

但是...但是,如果需要的话,它将如何在foreach语句中将Delegate转换为Action呢?
是foreach在幕后使用显式强制转换吗?

das*_*ght 5

foreach如果需要,如何将委托中的Delegate转换为Action,并在随后编译时抱怨显式转换?

长话短说,foreach声明为您添加了一个明确的演员表。这样做是为了在引入泛型之前与C#兼容。想法是简化无类型集合的迭代,例如

// Use an untyped list which stores System.Object objects
ArrayList list = new ArrayList();
list.Add(1);
list.Add(2);
list.Add(4);
list.Add(8);
foreach (int x in list) { // C# inserts a cast for you
    Console.WriteLine(x);
}
Run Code Online (Sandbox Code Playgroud)

因为类型转换在其中foreach,所以代码可以编译,但是可能会在运行时中断。First()另一方面,LINQ 充分利用了静态类型检查的功能,要求您指定显式强制转换。