How can I obtain return type from method passed as an argument in another method with Roslyn?

好久不见. 提交于 2020-01-06 04:50:08

问题


Lets say that I have a code:

public class Test {
    private readonly IFactory _factory;
    private readonly ISomeClass _someClass;

    public Test(IFactory factory, ISomeClass someClass)
    {
        _factory = factory;
        _someClass = someClass;
    }

    ....

    public void TestMethod() {
        _someClass.Do(_factory.CreateSomeObject());
    }
}

public class Factory {
    public SomeObject CreateSomeObject() {
        return new SomeObject();
    }
}

public class SomeClass {
    public void Do(SomeObject obj){
        ....
    }
}

I would like to get return type of CreateSomeObject from InvocationExpressionSyntax of someClass.Do(_factory.CreateSomeObject()); Is it possible?

I have a list of arguments (ArgumentSyntax) but I have no clue how to get method return type from ArgumentSyntax. Is there better and easier way to do it other then scanning a solution for Factory class and analyzing CreateSomeObject method?


回答1:


Yes, it is possible. You would need to use Microsoft.CodeAnalysis.SemanticModel for it.

I assume you have CSharpCompilation and SyntaxTree already available, so you would go in your case with something like this:

SemanticModel model = compilation.GetSemanticModel(tree);           
var methodSyntax = tree.GetRoot().DescendantNodes()
    .OfType<MethodDeclarationSyntax>()
    .FirstOrDefault(x => x.Identifier.Text == "TestMethod");
var memberAccessSyntax = methodSyntax.DescendantNodes()
    .OfType<MemberAccessExpressionSyntax>()
    .FirstOrDefault(x => x.Name.Identifier.Text == "CreateSomeObject");
var accessSymbol = model.GetSymbolInfo(memberAccessSyntax);
IMethodSymbol methodSymbol = (Microsoft.CodeAnalysis.IMethodSymbol)accessSymbol.Symbol;
ITypeSymbol returnType = methodSymbol.ReturnType;

Once you get the desired SyntaxNode out of the semantic model, you need to get its SymbolInfo and properly cast it, to get its ReturnType which does the trick.



来源:https://stackoverflow.com/questions/59407976/how-can-i-obtain-return-type-from-method-passed-as-an-argument-in-another-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!