简体   繁体   English

如何使用Roslyn检测类是否使用Linq?

[英]How to detect if a class uses Linq using Roslyn?

Using Roslyn , I would like to detect if a class uses Linq . 使用Roslyn ,我想检测一个类是否使用Linq

Assuming some code like: 假设一些代码如下:

//...
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };       
var lowNums = 
    from n in numbers 
    where n < 5 
    select n; 
//...

Assume also that the file this code does not include using System.Linq; 还假定此代码文件不包含 using System.Linq; 的文件 using System.Linq;

I would like to be able to detect that there is a linq statement in the file and (say) automatically add using System.Linq . 我希望能够检测到文件中有linq语句,并(例如) using System.Linq自动添加。 I would like to detect either query or method syntax for Linq. 我想检测Linq的查询或方法语法。

Is there a way I can detect this using Roslyn? 有什么方法可以使用Roslyn进行检测吗? I just want to know if the code is using Linq or not, and dont want to do any further processing. 我只想知道代码是否在使用Linq,并且不想做任何进一步的处理。

Given a syntax tree, you can simply search for nodes of SyntaxKind.QueryExpression or related node types. 给定语法树,您可以简单地搜索SyntaxKind.QueryExpression节点或相关节点类型。

For more information, open the file in VS2015 and look at the syntax visualizer to see exactly what the syntax tree looks like. 有关更多信息,请在VS2015中打开文件,然后查看语法可视化工具以确切查看语法树的外观。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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