[英]Derive parameter type with 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? 如何确定参数的类型,以便确保它是我感兴趣的类型?
Getting the actual Type
of a parameter can't be done so easily with Roslyn. 使用Roslyn很难轻松获得参数的实际
Type
。 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). 您可以如下所示获得
TypeSyntax
和ITypeSymbol
,但是除非使用反射,否则就无法真正获得Type
对象(据我所知)。
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???
}
You might want to check out this related question as well. 您可能还想看看这个相关问题 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.