简体   繁体   中英

Produce well formatted nullable type syntax with Roslyn when generating language agnostic code

I'm using Roslyn to create what should be a language agnostic code generator for some sort of data access layer. It will use metadata to output the desired code. It is expected to return C# and VB.NET versions of the code.

Current implementation is generating the desired output however the nullable types are not well formatted , the output contains extra white spaces.

Is there an option to ensure the nullable type generated by SyntaxGenerator.NullableTypeExpression return a well formatted - no white spaces - declaration?

Code Snippets

This is where SyntaxGenerator.NullableTypeExpression is used to return a SyntaxNode corresponding to the property type.

    private SyntaxNode ToTypeExpression(Type type, bool nullable, SyntaxGenerator generator)
    {

        SyntaxNode baseType;
        SyntaxNode propType;

        SpecialType specialType = ToSpecialType(type);

        if(specialType == SpecialType.None)
        {
            baseType = generator.IdentifierName(type.Name);                
        }
        else
        {
            baseType = generator.TypeExpression(specialType);
        }

        if (nullable && type.IsValueType)
        {
            propType = generator.NullableTypeExpression(baseType);
        }
        else
        {
            propType = baseType;
        }

        return propType;

    }

This is the generated VB.NET code:

    Public Property Salary As Integer?
        Get
            Return GetAttributeValue(Of Integer?)("salary").Value
        End Get

        Set(value As Integer?)
            SetPropertyValue("Salary", "salary", value)
        End Set
    End Property

This is the C# code, note the white spaces :

    public int ? Salary
    {
        get
        {
            return GetAttributeValue<int ? >("salary").Value;
        }

        set
        {
            SetPropertyValue("Salary", "salary", value);
        }
    }

Using Formatter.Format as suggest here: Generating well-formatted syntax with Roslyn , removed the undesired white spaces.

        string textOutput;
        var sb = new StringBuilder();

        var result = generator.CompilationUnit(declarations);

        var formattedResult = Formatter.Format(result, workspace);

        using (StringWriter writer = new StringWriter(sb))
        {
            formattedResult.WriteTo(writer);
            textOutput = writer.ToString();
        }

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