![](/img/trans.png)
[英]Why does the C# compiler allow a cast to be performed with Linq but not with parentheses?
[英]Why does the C# compiler go mad on this nested LINQ query?
嘗試編譯以下代碼,你會發現編譯器需要> 3 GB的RAM(我機器上的所有可用內存)和很長的編譯時間(實際上我在10分鍾后得到IO異常)。
using System;
using System.Linq;
public class Test
{
public static void Main()
{
Enumerable.Range(0, 1).Sum(a =>
Enumerable.Range(0, 1).Sum(b =>
Enumerable.Range(0, 1).Sum(c =>
Enumerable.Range(0, 1).Sum(d =>
Enumerable.Range(0, 1).Sum(e =>
Enumerable.Range(0, 1).Sum(f =>
Enumerable.Range(0, 1).Count(g => true)))))));
}
}
任何人都可以解釋這種奇怪的行為嗎?
CS Version: Microsoft (R) Visual C# Compiler version 4.0.30319.17929 OS Name: Microsoft Windows 7 Ultimate OS Version: 6.1.7601 Service Pack 1 Build 7601
我相信它與類型推斷和/或lambda生成有關(當類型推斷必須與正常方向相反時),結合重載決策。 不幸的是,只提供類型參數對情況沒有幫助(它可能仍然需要執行類型檢查)。
在分析了lambdas之后,以下代碼在邏輯上應該是您的等效代碼,編譯沒有問題:
static void Main()
{
var x = Enumerable.Range(0, 1).Sum(a);
}
private static int a(int a)
{
return Enumerable.Range(0, 1).Sum(b);
}
private static int b(int b)
{
return Enumerable.Range(0, 1).Sum(c);
}
private static int c(int c)
{
return Enumerable.Range(0, 1).Sum(d);
}
private static int d(int d)
{
return Enumerable.Range(0, 1).Sum(e);
}
private static int e(int e)
{
return Enumerable.Range(0, 1).Sum(f);
}
private static int f(int f)
{
return Enumerable.Range(0, 1).Count(g);
}
private static bool g(int g)
{
return true;
}
我相信Eric Lippert之前發布的類型推斷是C#編譯器中的一個地方,其中(某些問題)可能會迫使編譯器嘗試解決NP-Complete問題,而其唯一真正的策略(如此處)是強力的。 如果我能找到相關的參考文獻,我會在這里添加它們。
我能找到的最好的參考就是這里埃里克的討論事實上,它是重載解析的工作,使真正的成本-記住, Enumerable.Sum有10個重載接受一個lambda /方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.