简体   繁体   English

如何在Roslyn中检查方法参数类型/返回类型是否通用?

[英]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. 在这里,我想返回method变量的所有类型的参数,这些类型不是通用的,但是我在API中找不到任何内容来过滤结果。

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: 如果您具有ArgumentListSyntax ,因此有零个或多个ArgumentSyntax es( ArgumentListSyntax.Arguments ),则可以从参数表达式中获取类型信息:

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

And from there, the IsGenericType property. 从那里开始,是IsGenericType属性。 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 : 如果你有一个MethodDeclarationSyntax方法的对象,你可以看到,如果ReturnType属性是一个类型的GenericNameSyntax

Debug.Assert(methodDeclaration.ReturnType is GenericNameSyntax);

cast to GenericNameSyntax to get more information about the generic type like type arguments. GenericNameSyntax转换为GenericNameSyntax以获取有关泛型(如类型GenericNameSyntax更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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