我正在使用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;
请告知我如何获得预期的结果。
对于记录,您只需添加原始语法节点中的琐事:
var newFieldType = SyntaxFactory.ParseName("System.Windows.Forms.UserControl")
.WithTriviaFrom(fieldType);
我会用这个“单行”来完成所有的工作:
var newField = field.WithDeclaration(
field.Declaration.WithType(
SyntaxFactory.ParseName("System.Windows.Forms.UserControl")
.WithTriviaFrom(field.Declaration.Type)));