[英]How do I change a field type using FieldTypeDeclaration ( Roslyn )
我正在使用Visual Studio项目类型-独立代码分析工具。 我正在使用以下代码,但是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)));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.