如何基于Visual Studio中的文件名以编程方式对C#.cs文件进行更改?

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

我将如何以编程方式更改类,例如根据类/文件名在Visual Studio(C#)中添加注释?

例如

之前:

using System;
using System.Collections.Generic;
using System.Text;

namespace ChangingCode.Lib
{
    public class ChangeThisClass
    {
        public void Method()
        {

        }
    }
}

之后:

using System;
using System.Collections.Generic;
using System.Text;

//This Got Added Somehow
//Is it possible?

namespace ChangingCode.Lib
{
    public class ChangeThisClass
    {
        public void Method()
        {

        }
    }
}
c# code-generation visual-studio-2019 visual-studio-extensions vsix
2个回答
1
投票

[不幸的是,CodeDom没有附带任何C#解析器实现(尽管它是got an interface)。但是,有很多C#解析器可用(有关更多信息,请参见this SO answer。)>

假设您决定使用NRefactory,然后添加注释就变成了更改AST的问题:

    var compiledUnit = ICSharpCode.NRefactory.CSharp.SyntaxTree.Parse(File.ReadAllText(@"D:\file.cs"));

    var namespaceNode = compiledUnit.Children.First(n => (n.GetType() == typeof(NamespaceDeclaration))) as NamespaceDeclaration; // find the start of namespace declaration
    var parent = namespaceNode.Parent; // get reference to file root since you're adding nodes above namespace
    parent.InsertChildAfter(namespaceNode.PrevSibling, new Comment("This Got Added Somehow"), Roles.Comment);
    parent.InsertChildAfter(namespaceNode.PrevSibling, new Comment("Is it possible?"), Roles.Comment);              
    // save it all back
    File.WriteAllText(@"D:\file.cs.modified.txt", compiledUnit.ToString());

1
投票

要实现这一目标],我想您可以创建一个包含任何自定义内容的父模板,然后在项目中使用该模板。

© www.soinside.com 2019 - 2024. All rights reserved.