是否可以使用C#中的委托返回方法的代码(作为字符串)?

时间:2012-03-07 19:48:09

标签: c# delegates

我会举例说明,因为我不确定我是否正确地提出这个问题(英语不是我的主要语言,而且我还在学习C#)。

我已经开始浏览Project Euler,并决定创建一个应用程序来跟踪我的结果,并将我的小C#知识用于测试。

在一个特定的类中,我保存用于解决每个问题的静态函数。

static class Answers()
{
  public static string A1(){...}
  public static string A2(){...}
  public static string A3(){...}
  //it goes on
}

问题对象将像这样创建(问题类定义和运行时对象创建)。

class Problem
{
  public string Description;
  public Solution SolutionFinder;

  public Problem(string Desc, Solution Solver)
  {
    this.Description = Desc;
    this.SolutionFinder = Solver;
  }

  public delegate string Solution();

  public string SolveProblem()
  {
    return SolutionFinder.Invoke();
  }
}

这是我的表单创建代码:

{
  ...
  List<Problem> Euler = new List<Problem>();
  Euler.Add(new Problem("Find the sum of all the multiples of 3 or 5 below 1000.", Answers.A1));
  Euler.Add(new Problem("By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.", Answers.A2));
  Euler.Add(new Problem("What is the largest prime factor of the number 600851475143 ?", Answers.A3));
  ...
}

我让班级甚至代表的事情都能正常工作,我很高兴。然后我终于决定在表格上展示整件事。 我想要展示的是:每当我使用我的表单解决问题时,问题的描述(已完成)和每个方法的代码(无论是在A1,A2等内部)。

这是清楚的吗?这只是我希望我的表单显示结果和如何我得到每个问题的解决方案,但无需重新键入每个方法的内容只是为了显示 - 方法已经存在。

请不要介意杂乱的代码和公众成员的过度使用:我理解这是一个不好的做法,但现在我只是想通过这个个人项目,我相信这样做是可以的这只是一个小小的学习经历。

感谢。

[编辑] 我正在寻找的格式是:

void UpdateForm(int Current)
{
  Problem CurrentProblem = Euler[Current-1];
  string Desc = CurrentProblem.Description;
  string Code = CurrentProblem.SolutionFinder.Method.ReturnType.Name;
  //I got this far, but I need to display more than just the name of the method!
  ...
}

澄清

鉴于方法:

public static string A1() {
    var answer = 1 + 1;
    return answer.ToString();
}

是否可以在字符串中获取以下行??

var answer = 1 + 1;
return answer.ToString();

5 个答案:

答案 0 :(得分:3)

虽然这不是最好的方法,但是如果通过源文件的属性(右键单击/属性)将“复制到输出目录”值设置为“始终复制”(或“复制如果更新”),则可以自己解析代码文件,同时优化您的编码风格。

要添加,您是否知道除了源代码转储外,您基本上正在重建NUnit?

答案 1 :(得分:2)

由于在运行时代码是IL(中间语言),因此您实际上没有可读代码 无论如何,您可以使用反射创建一个动态反编译器,或使用第三方库如this onethis one来反编译方法......但我不知道他们是否公开了一些API,我只知道它们是GUI工具。

答案 2 :(得分:1)

您可能会考虑将您的解决方案(源代码)存储在文本文件中(例如,Problem1.projecteuler,ProblemN.projecteuler)并加载这些文本文件以用于显示和编译/执行插件样式。查看System.Reflection命名空间,并对&#34; C#插件教程&#34;进行一些网络搜索。或者一些这样的开始。

答案 3 :(得分:0)

valeriano你的静态方法可能是Linq表达式,然后你可以遍历表达式的每个节点。使用Reflection也有效,但您需要更多代码

答案 4 :(得分:0)

没有简单的方法从字符串运行代码(即:方法的内容),因为C#在其可执行文件启动之前已经编译过。

但是,您可以使用Reflection和Diagnostics进行操作,但这需要您在调试模式下运行代码。如果它只是一个小应用程序,这应该不是问题。但是,在调试模式下运行时,较大的应用程序会遇到性能问题。

了解更多信息:Execute a string in C# 4.0