使用 Roslyn 在区域琐事之间插入代码 [英] Inserting Code Between Region Trivia With Roslyn

查看:29
本文介绍了使用 Roslyn 在区域琐事之间插入代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Roslyn 中的区域指令后插入变量声明?我希望能够做这样的事情:

How can I insert a variable declaration after a region directive in Roslyn? I'd like to be able to do something like going from this:

class MyClass 
{
    #region myRegion
    #endregion
}

为此:

class MyClass 
{
    #region myRegion
    private const string myData = "somedata";
    #endregion 
}

我似乎找不到任何以这种方式处理琐事的例子.

I can't seem to find any examples that deal with trivia in this manner.

推荐答案

这对于 CSharpSyntaxRewriter,因为 #region #endregion 都在同一个 SyntaxTriviaList,您必须将其拆分并找出要创建的内容.不打扰所有复杂性的最简单方法是创建相应的 TextChange 并修改 SourceText.

That's quite tricky to do with a CSharpSyntaxRewriter, because both the #region <name> and #endregion end up in the same SyntaxTriviaList, which you'd have to split out and figure out what to create instead. The simplest way to not bother with all the intricacies, is to create the corresponding TextChange and modify the SourceText.

var tree = SyntaxFactory.ParseSyntaxTree(
@"class MyClass
{
    #region myRegion
    #endregion
}");

// get the region trivia
var region = tree.GetRoot()
    .DescendantNodes(descendIntoTrivia: true)
    .OfType<RegionDirectiveTriviaSyntax>()
    .Single();

// modify the source text
tree = tree.WithChangedText(
    tree.GetText().WithChanges(
        new TextChange(
            region.GetLocation().SourceSpan,
            region.ToFullString() + "private const string myData = \"somedata\";")));

之后,tree是:

class MyClass 
{
    #region myRegion
private const string myData = "somedata";
    #endregion
}

这篇关于使用 Roslyn 在区域琐事之间插入代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆