简体   繁体   中英

How to check if method parameter type/return type is generic, in Roslyn?

As stated in the title, I want to check if a method params are generic + if the return type of a method is generic.

For example:

    public ISet<string> Collect(MethodDeclarationSyntax method, SemanticModel semanticModel)
    {
        return method
            .ParameterList
            .Parameters
            .Select(x => x.Type.ToString())
            .ToImmutableHashSet();
    }

Here I want to return all the types of the params for the method variable, that are not generic, but I can't find anything in the API to filter the results.

I have the same problem when checking if the return type of a method is generic.

It depends on what you have to work with. If you have an ArgumentListSyntax and thus zero or more ArgumentSyntax es ( ArgumentListSyntax.Arguments ), you can get the type info from the argument expression:

var type = model.GetTypeInfo(argument.Expression).Type as INamedTypeSymbol;

And from there, the IsGenericType property. For example:

Debug.Assert(type.IsGenericType);

And if you have a MethodDeclarationSyntax object of the method, you can see if the ReturnType property is a type of GenericNameSyntax :

Debug.Assert(methodDeclaration.ReturnType is GenericNameSyntax);

cast to GenericNameSyntax to get more information about the generic type like type arguments.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM