2016-08-18 80 views
0

的類型我有以下代碼:GetTypeInfo的失敗中找到「VAR」

public class ParallelLinqAsSequential 
{ 
    private List<Customer> _orders; 

    private void Method() 
    { 
     var query = (_orders.AsParallel().OrderBy(ord => ord.CustomerID).Select(ord => new 
     { 
      Date = ord.OrderDate 
     })).AsSequential().Take(5); 
    } 

    private class Customer 
    { 
     public string CustomerID; 
     public DateTime OrderDate { get; set; } 
    } 
} 

我期待在調用通過命名變量語義模型時,「查詢」它能夠將其推斷爲具有「DateTime」類型字段的匿名類型Enumerable。但它失敗並顯示ErrorType。

在Visual Studio中,您可以看到它,如下圖所示。

enter image description here

我使用從羅斯林得到這個代碼是:

public void GetType(SyntaxTree tree) 
{ 
      var Mscorlib = MetadataReference.CreateFromFile(typeof(object).Assembly.Location); 
      var compilation = CSharpCompilation.Create("RoslynVar", syntaxTrees: new[] { tree }, references: new[] { Mscorlib }); 


      VariableDeclarationSyntax variable = ... // get the relevant variable 
      TypeInfo symbolInfo = semanticModel.GetTypeInfo(variable.Type); 
} 
+0

你能告訴用來做此代碼:

或者,你可以從VariableDeclaratorSyntax.Initializer,這是var query =後的部分得到了更具體的ITypeSymbol? –

+1

檢查語義模型的診斷。也許你錯過了對System.Core的引用 – user2697817

回答

2

你需要得到的query變量的語義信息,而不是varTypeSyntaxvariable.Type得到)部分的var query聲明。在你的情況,這將是:

var typeSymbol = 
    ((ILocalSymbol)semanticModel.GetDeclaredSymbol(variable.Variables[0])).Type; 

你得到ITypeSymbol其中TypeInfo的usaful部分。

var typeSymbol = 
    semanticModel.GetOperation(variable.Variables[0].Initializer.Value).Type;