【问题标题】:Produce well formatted nullable type syntax with Roslyn when generating language agnostic code在生成与语言无关的代码时,使用 Roslyn 生成格式良好的可空类型语法
【发布时间】:2017-07-13 01:55:10
【问题描述】:

我正在使用 Roslyn 为某种数据访问层创建与语言无关的代码生成器。 它将使用元数据来输出所需的代码。 预计会返回 C# 和 VB.NET 版本的代码。

当前实现正在生成所需的输出,但是 可为空的类型格式不正确,输出包含额外的空格。

是否有一个选项可以确保SyntaxGenerator.NullableTypeExpression 生成的可为空类型返回格式正确的 - 没有空格 - 声明?

代码片段

这是SyntaxGenerator.NullableTypeExpression 用于返回与属性类型对应的 SyntaxNode 的地方。

    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;

    }

这是生成的 VB.NET 代码:

    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

这是 C# 代码,注意空格

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

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

【问题讨论】:

  • 你有什么问题?
  • Echoing Ed,这里的错误信息、预期条件等是什么?
  • 你试过.W‌​ithAdditionalAnnotat‌​ions(Formatter.Annot‌​ation)吗?
  • 对不起,伙计们,但我不明白“否决票”。 @EdPlunkett 和Kirk,问题在帖子主题上,以问号结尾:-) 没有“错误消息”,但“意外情况”是可空值的C# 版本上的额外空白。它不会阻止它编译,但看起来也不正确。
  • @Ebrito 显然,您已经让 Roslyn 正确地生成了您想要的确切代码。这是一个关于格式化生成代码的问题,与标题相反。也许这就是 -1 的意义所在;不能说,因为不是我。

标签: c# code-generation roslyn roslyn-code-analysis


【解决方案1】:

按照此处的建议使用Formatter.FormatGenerating well-formatted syntax with Roslyn,删除不需要的空格。

        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();
        }

【讨论】:

    猜你喜欢
    • 2016-02-01
    • 2012-11-10
    • 2015-03-06
    • 2018-01-25
    • 2019-01-07
    • 1970-01-01
    • 2018-07-03
    • 1970-01-01
    • 2010-09-20
    相关资源
    最近更新 更多