3

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;

期待される結果を得る方法を教えてください。

4

2 に答える 2

3

記録として、元の構文ノードからトリビアを追加するだけです。

var newFieldType = SyntaxFactory.ParseName("System.Windows.Forms.UserControl")
                                .WithTriviaFrom(fieldType);
于 2015-10-11T21:06:58.920 に答える
0

すべての作業を行うために、この「ワンライナー」を使用します。

var newField = field.WithDeclaration(
                    field.Declaration.WithType(
                            SyntaxFactory.ParseName("System.Windows.Forms.UserControl")
                                         .WithTriviaFrom(field.Declaration.Type)));
于 2016-06-14T11:52:53.720 に答える