Visual Studio의 파일 이름을 기반으로 프로그래밍 방식으로 C # .cs 파일을 변경하는 방법은 무엇입니까?

AFM 호라이즌

클래스 / 파일 이름을 기반으로 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()
        {

        }
    }
}
동쪽

불행히도 CodeDom에는 C # 파서 구현이 함께 제공되지 않습니다 ( 해당 인터페이스가 있지만 ). 그러나 사용할 수있는 C # 파서가 많이 있습니다 (자세한 내용은 이 SO 답변 참조 ).

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());

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

Related 관련 기사

뜨겁다태그

보관