如何使用FieldTypeDeclaration(Roslyn)更改字段类型

问题描述 投票:2回答:2

我正在使用visual studio项目类型 - Stand-Alone Code Analysis Tool。我使用以下代码,但ToString()显示意外的结果。

static void Main(string[] args)
{
    var classDoc = @"public class SomeClass{
            private SomeOtherClass someOtherClass;
        }";

    SyntaxTree classTree=SyntaxFactory.ParseSyntaxTree(classDoc);
    var classDecl = (ClassDeclarationSyntax)classTree.GetRoot().DescendantNodes()
        .First(d => d is ClassDeclarationSyntax);

    var field = classDecl.Members.OfType<FieldDeclarationSyntax>().First();
    var fieldType = field.Declaration.Type;
    var newFieldType = SyntaxFactory.ParseName("System.Windows.Forms.UserControl");
    var newField=field.ReplaceNode(fieldType, newFieldType);
    var newFieldStr = newField.ToString();
}

newFieldStr的价值是

private System.Windows.Forms.UserControlsomeOtherClass;

请告知我如何获得预期的结果。

c# roslyn roslyn-code-analysis
2个回答
3
投票

对于记录,您只需添加原始语法节点中的琐事:

var newFieldType = SyntaxFactory.ParseName("System.Windows.Forms.UserControl")
                                .WithTriviaFrom(fieldType);

0
投票

我会用这个“单行”来完成所有的工作:

var newField = field.WithDeclaration(
                    field.Declaration.WithType(
                            SyntaxFactory.ParseName("System.Windows.Forms.UserControl")
                                         .WithTriviaFrom(field.Declaration.Type)));
© www.soinside.com 2019 - 2024. All rights reserved.