Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/264.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么LINQ'需要显式强制转换;s First(),但在foreach中不是必需的?_C# - Fatal编程技术网

C# 为什么LINQ'需要显式强制转换;s First(),但在foreach中不是必需的?

C# 为什么LINQ'需要显式强制转换;s First(),但在foreach中不是必需的?,c#,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 firstD

有人能解释一下这段代码是如何工作的吗

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
但是。。。但是,如果它需要显式转换为编译后的类型,它如何将委托转换为foreach语句中的操作??
foreach是否在幕后使用显式强制转换

如果需要显式强制转换,它如何将委托转换为
foreach
语句中的操作

长话短说,
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);
}

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

foreach在幕后使用显式转换吗??当用这种方式时,是的。非泛型时间结转:)@IvanStoev但编译器如何知道强制转换是可能的?因为
Action
是委托类型。
Func
EventHandler
和许多其他文件也是如此。所选的副本并不理想,因为OP的问题是有关强制转换的
foreach
的具体比较,以及缺少强制转换的
First()
。相比之下,复制是关于C#没有在
foreach
内部应用可用的用户定义转换,这不是一回事。我投票决定重新讨论这个问题。@dasblinkenlight上帝保佑你们,愿望是一种让投票率回升的方式;(如果它是显式的,为什么我不能将委托转换为其他类型,如string或int??您可以输入foreach,如
foreach(列表中的字符串s)
,但它在运行时会失败并抛出invalidcastexception@EhsanSajjadC#将在编译时禁止此操作,就像使用显式强制转换()@MohsenShakiba…因为委托不是string或int类型。@MohsenShakiba C#将在
foreach
和显式强制转换中检查强制转换是否可行。在这两种情况下,您都会得到编译时错误。