如何在类中提取完整的方法?

时间:2016-10-25 19:30:58

标签: c# text methods

我试图提取一个在cs文件中的完整方法。 例如..假设我们有一个这样的类......

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GetMethodNm
{
class MyClass
{

    public int ComplexMethod(int param1, int myCustomValue)
    {
        if (param1 == myCustomValue)
        {
            return 54;
        }
        else
        {
            return 0;
        }
    }

    public string ComplexMethodV(int param1, int myCustomValue)
    {
        if (param1 < myCustomValue)
        {
            return "300";
        }
        else
        {
            return "My custom value to return";
        }
    }

    public bool ComplexMethodX(int param1, int myCustomValue)
    {
        if (param1 == myCustomValue)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
}
}

然后我需要提取读取cs文件的方法 ComplexMethodV ..我该怎么做?我尝试过反射,但我只能得到它里面的名字和一些东西..但是我需要内部的文字方法。

1 个答案:

答案 0 :(得分:2)

使用这样的Roslyn任务非常容易。在项目中添加NuGet包Microsoft.CodeAnalysis.CSharp,然后使用以下代码

        public string ComplexMethodV(int param1, int myCustomValue)
        {
            if (param1 < myCustomValue)
            {
                return "300";
            }
            else
            {
                return "My custom value to return";
            }
        }

这将输出文本

var nodes = //get nodes

for(var i = 0; i < nodes.length; i++) {
  var isThirdIteration = (i + 1) % 3 === 0;

  if (isThirdIteration) {
    this.className += ' newClassName';
  }
}​

有关如何解析整个解决方案的更多高级教程,请参阅the Wiki