How to get TypeSyntax from TypeDeclarationSyntax

I am writing a simple Roslyn generator that generates an implementation of an interface, so I want to get TypeSyntax

from TypeDeclarationSyntax

, because of the following code:

// Our generator is applied to any class that our attribute is applied to.
var applyToInterface = (InterfaceDeclarationSyntax)applyTo;

// Trying to implement this interface
var clientClass = SyntaxFactory.ClassDeclaration(SyntaxFactory.Identifier(applyToInterface.Identifier.ValueText + "Client"))
    .WithModifiers(SyntaxTokenList.Create(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
    .WithBaseList(SyntaxFactory.SimpleBaseType(applyToInterface.???));

      

However, I don't see any way to create TypeSyntax other than SyntaxFactory.ParseTypeName

. But I don't want to get the interface name and then convert it back to the type due to possible errors (like +

generic characters instead of dot, etc.).

What is the most convenient and recommended way to perform this operation? I am currently using

var clientClass = SyntaxFactory.ClassDeclaration(SyntaxFactory.Identifier(applyToInterface.Identifier.ValueText + "Client"))
    .WithModifiers(SyntaxTokenList.Create(SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
    .AddBaseListTypes(SyntaxFactory.SimpleBaseType(SyntaxFactory.ParseTypeName(applyToInterface.Identifier.ValueText)));

      

But I'm not sure if it's fixed correctly.

+3


source to share


1 answer


I believe the way you do it is correct, due to lack of information from Roslyn, I usually check their source to use internal examples to test my samples. I found this sample for searching WithBaseList

var implementedInterfaceTypeSyntax = extractedInterfaceSymbol.TypeParameters.Any()
            ? SyntaxFactory.GenericName(
                SyntaxFactory.Identifier(extractedInterfaceSymbol.Name),
                SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(extractedInterfaceSymbol.TypeParameters.Select(p => SyntaxFactory.ParseTypeName(p.Name)))))
            : SyntaxFactory.ParseTypeName(extractedInterfaceSymbol.Name);

var baseList = typeDeclaration.BaseList ?? SyntaxFactory.BaseList();
var updatedBaseList = baseList.WithTypes(SyntaxFactory.SeparatedList(baseList.Types.Union(new[] { SyntaxFactory.SimpleBaseType(implementedInterfaceTypeSyntax) })));

      



In this case, they use the symbol to generate the type.

+1


source







All Articles