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

时间:2015-10-11 17:30:42

标签: c# roslyn roslyn-code-analysis

我正在使用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;

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

2 个答案:

答案 0 :(得分:3)

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

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

答案 1 :(得分:0)

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

select user_id, 100.0 * count(case when cnt = 2 then 1 end) / count(*)
from
(
  select 
    user_id,
    count(*) over (partition by group_id) as cnt -- cnt = 2 marks a "two" group
  from tbl_groupuser
)
group by user_id
having count(case when cnt = 2 then 1 end) > 0; -- user in at least one "two" group