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. 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???
}
You might want to check out this related question as well.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.