简体   繁体   中英

Getting the name of a type of generic property of class definition using Roslyn

I have a class defined as below:

class Derived
{
    public int t { get; set; }
    public List<Child> Childs { get; set; }
}

I want to get the System.Type for every property of the class. This is what I have currently:

var properties = node.DescendantNodes().OfType<PropertyDeclarationSyntax>();

var symbolDisplayFormat = new SymbolDisplayFormat(
    typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces
);

foreach (var property in properties) 
{
    var typeSymbol = context.SemanticModel.GetSymbolInfo(property.Type).Symbol as INamedTypeSymbol;
    string name = typeSymbol.ToDisplayString(symbolDisplayFormat);
}

Where node is a ClassDeclarationSyntax .

This code works fine for the property t ; the name of the type of the property is returned System.Int32 . However, for the property Childs (it's a type with a generic argument) I get a null typeSymbol , which is not the System.Type for this property that's expected.

How can I get the type of property of a generic type from a class definition using Roslyn?

You should use SemanticModel.GetTypeInfo instead of SemanticModel.GetSymbolInfo to retrieve corresponding ITypeSymbol from node:

...
foreach (var property in properties) 
{
    var info = context.SemanticModel.GetTypeInfo(property);
    var typeSymbol = info.Type ?? info.ConvertedType; 
    ...
}

如果你想要泛型的(第一个)参数类型,你可以使用:

TypeSyntax type = (property.Type as GenericNameSyntax).TypeArgumentList.Arguments[0];

I managed to get the generic type information with:

if (type is INamedTypeSymbol nType) //type is ITypeSymbol
{
    bool isGeneric = nType.IsGenericType;
    int typeArgumentsCount = nType.TypeArguments.Count();
    ...
}

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