简体   繁体   中英

GetTypeInfo from semantic model in Roslyn fails to find type of “var”

I have the following code:

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; }
    }
}

I was expecting that when calling the semantic model over the variable named "query" it would be able to infer it as an Enumerable of anonymous type with a field of "DateTime" type. But it fails and shows ErrorType.

While in Visual Studio you can see it as in the image below.

在此处输入图片说明

The code I am using to get this from the Roslyn is:

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);
}

You need to get the semantic info for the query variable, not the var ( TypeSyntax you get from variable.Type ) part of the var query declaration. In your case this would be:

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

You get the ITypeSymbol which the usaful part of TypeInfo .

Alternatively, you can get a more specific ITypeSymbol from the VariableDeclaratorSyntax.Initializer , which is the part after var query = :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM