简体   繁体   English

如何在Roslyn上获得扩展方法?

[英]How to get extension methods on Roslyn?

I need to list all extension methods found on the file. 我需要列出文件中找到的所有扩展方法。

This is what I'm doing so far (looks like it's working): 这是我到目前为止所做的(看起来它正在工作):

var methods = nodes.OfType<MethodDeclarationSyntax>();    
var extensionMethods = methods.Where(m => 
        m.Modifiers.Any(t => t.Kind == SyntaxKind.StaticKeyword) 
        && m.ParameterList.Parameters.Any(p => 
            p.Modifiers.Any(pm => pm.Kind == SyntaxKind.ThisKeyword)));

Even though I couldn't test all cases it looks like this is working. 即使我无法测试所有情况,但看起来这样做有效。 But I was wondering if there was a more concise way to approach this solution. 但我想知道是否有更简洁的方法来解决这个问题。

Is there some sort of IsExtension or some SyntaxKind.ExtensionMethod? 是否有某种IsExtension或一些SyntaxKind.ExtensionMethod? I took a look but could not find anything obvious, at least. 我看了看,但至少找不到任何明显的东西。

I'm using the latest Roslyn Sept/12 我正在使用最新的Roslyn Sept / 12

You're working at the syntactic level and at this level, there is no such thing as “extension method”. 你在语法层面工作,在这个层面上,没有“扩展方法”这样的东西。 What you can do is to get semantic information (called Symbol ) for each method and there you will see whether it is an extension method. 你可以做的是为每个方法获取语义信息(称为Symbol ),在那里你将看到它是否是一个扩展方法。 Something like: 就像是:

SyntaxTree tree = …
var compilation = Compilation.Create("foo").AddSyntaxTrees(tree);
var model = compilation.GetSemanticModel(tree);

var methods = …
var extensionMethods =
   methods.Where(m => model.GetDeclaredSymbol(m).IsExtensionMethod);

This means your code actually needs to compile and you will also have to add any necessary references to the compilation. 这意味着您的代码实际上需要编译,您还必须添加任何必要的编译引用。

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

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