简体   繁体   English

使用Roslyn检测lambda表达式的长度

[英]Detect the length of a lambda expression using Roslyn

I'm wondering how could one possibly detect the length (number of lines) when analyzing code using the Roslyn compiler. 我想知道在使用Roslyn编译器分析代码时,怎么可能检测到长度(行数)。 At the moment, I'm developing a law which prohibited the use of lambdas longer than 10 lines. 目前,我正在制定一项禁止使用超过10行的lambdas的法律。

Looking at the example below, how could I know that the simple lambda expression syntax has only one line ? 看下面的例子,我怎么知道简单的lambda表达式语法只有一行?

        // Data source. 
        int[] scores = { 90, 71, 82, 93, 75, 82 };

        // The call to Count forces iteration of the source 
        int highScoreCount = scores.Where(n => n > 80).Count();

EDITS What I would like to know, is exactly know the difference in the number of lines we can see in the lambda expression in the first example and in the one just below : 编辑我想知道的是,我们可以在第一个示例和下面的一个示例中看到我们在lambda表达式中可以看到的行数的差异:

   1: private IEnumerable<Book> BooksPublishedBetween1991and1997()
   2: {
   3:     return Books.FindAll(Book => {
   4:  
   5:         return Book.Published >= new DateTime(1991, 01, 01) &&
   6:         Book.Published <= new DateTime(1997, 12, 31);
   7:     
   8:     });
   9: } //Link to sample :  http://www.rvenables.com/2009/03/practical-introduction-to-lambda-expressions/

UPDATE UPDATE

It has been pointing out in the comments that my question is too broad. 它在评论中指出我的问题太宽泛了。 I'm going to try to simply it as much as I can. 我会尽可能地尝试简单。 I have done code analysis before using Roslyn to validate certain development usage users should have when developing client software. 在使用Roslyn验证开发客户端软件时用户应具有的某些开发用量之前,我已经完成了代码分析。 I have a general way to go through the nodes of the tree code (not sure if it's really called like that) by using a SyntaxNodeAnalysisContext object. 我有一个通用的方法来通过使用SyntaxNodeAnalysisContext对象来遍历树代码的节点(不确定它是否真的被称为)。 What I would like to know is when I'm looking for SimpleLambdaExpressionSyntax and ParenthesisedLambdaExpressionSyntax, is the way to look at the content of the lambda expression and know exactly on how many lines the code was written. 我想知道的是,当我在寻找SimpleLambdaExpressionSyntax和ParenthesisedLambdaExpressionSyntax时,是查看lambda表达式内容并确切知道代码编写行数的方法。

It sounds like you know how to get to the relevant syntax nodes ( SimpleLambdaExpressionSyntax and ParenthesizedLambdaExpressionSyntax ) and just need to know how long they are. 听起来你知道如何到达相关的语法节点( SimpleLambdaExpressionSyntaxParenthesizedLambdaExpressionSyntax ),只需知道它们有多长。

I think you just want something like this: 我想你只想要这样的东西:

var lineSpan = node.SyntaxTree.GetMappedLineSpan(node.Span);
var lines = lineSpan.EndLinePosition.Line - lineSpan.StartLinePosition.Line + 1;

There may be a more efficient or simpler way of doing it, but that should get you started. 可能有更高效或更简单的方法,但这应该让你开始。

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

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