使用 Roslyn 导出参数类型 [英] Derive parameter type with Roslyn
本文介绍了使用 Roslyn 导出参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了以下对象来遍历我的构造函数:
I have created the following object to walk my constructor:
internal class ConstructorWalker : CSharpSyntaxWalker
{
private string className = String.Empty;
private readonly SemanticModel semanticModel;
private readonly Action<string> callback;
public ConstructorWalker(Document document, Action<string> callback)
{
this.semanticModel = document.GetSemanticModelAsync().Result;
this.callback = callback;
}
public override void VisitConstructorDeclaration(ConstructorDeclarationSyntax node)
{
var typeToMatch = typeof(Dictionary<string, Func<GenericMobileRequest, Result<object>, Task>>);
var parameters = node.ParameterList;
foreach (var param in parameters.ChildNodes()) {
//This does not work... .Symbol is null
var paramType = ((IParameterSymbol)semanticModel.GetSymbolInfo(param).Symbol).Type;
if(paramType == typeToMatch) {
//PROFIT!!!
}
}
如何确定参数的类型以确保它是我感兴趣的类型?
How can I determine the type of the parameter so I can ensure it is of the type I am interested in?
推荐答案
使用 Roslyn 无法轻松获取参数的实际 Type
.您可以获得 TypeSyntax
和 ITypeSymbol
如下所示,但除非您使用反射,否则您无法真正获得 Type
对象(就我知道).
Getting the actual Type
of a parameter can't be done so easily with Roslyn. You can get the TypeSyntax
and ITypeSymbol
as shown below, but unless you use reflection you can't really get a Type
object (as far as I know).
string typeToMatchString = "Dictionary<string, Func<Exception, HashSet<object>, Task>>"
foreach (var parameter in node.ParameterList.Parameters)
{
var typeSyntax = parameter.Type;
var typeSymbol = semanticModel.GetTypeInfo(typeSyntax).Type;
// Maybe comparing the name is enough?
if (typeSymbol.ToDisplayString() == typeToMatchString)
//PROFIT???
}
您可能还想查看这个相关问题.
这篇关于使用 Roslyn 导出参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文