[英]How can I obtain return type from method passed as an argument in another method with Roslyn?
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());
我想获得的返回类型
CreateSomeObject
从InvocationExpressionSyntax
的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.我有一个参数列表(ArgumentSyntax),但我不知道如何从 ArgumentSyntax 获取方法返回类型。 Is there better and easier way to do it other then scanning a solution for
Factory
class and analyzing CreateSomeObject
method?除了扫描
Factory
类的解决方案并分析CreateSomeObject
方法之外,还有更好更简单的方法吗?
Yes, it is possible.对的,这是可能的。 You would need to use
Microsoft.CodeAnalysis.SemanticModel
for it.您需要为此使用
Microsoft.CodeAnalysis.SemanticModel
。
I assume you have CSharpCompilation and SyntaxTree already available, so you would go in your case with something like this:我假设您已经有 CSharpCompilation 和 SyntaxTree 可用,因此您可以使用以下内容:
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.一旦您从语义模型中获得所需的
SyntaxNode
,您需要获取它的SymbolInfo
并正确地转换它,以获得它的ReturnType
这一点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.