如何使用反射或替代以编程方式创建函数调用?

编程入门 行业动态 更新时间:2024-10-11 21:21:31
本文介绍了如何使用反射或替代以编程方式创建函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我是 Reflection 的新手.我希望有可能做我想做的事.我一直在通过 ProjectEuler 学习这门语言,我有一个名为 Problem 的基类.每个单独的 PE 问题都是一个单独的类,即问题 16.为了运行我的计算,我使用以下代码:

I'm a bit of a novice with Reflection. I'm hoping that it's possible to do what I'd like it to. I've been working through ProjectEuler to learn the language, and I have a base class called Problem. Every individual PE problem is a separate class, i.e. Problem16. To run my calculations, I use the following code:

using System; using Euler.Problems; using Euler.Library; namespace Euler { static class Program { [STAThread] static void Main() { Problem prob = new Problem27(); } } }

我现在已经完成了 50 道题,我想创建一个循环来运行它们.我的基类 Problem 有一个方法将问题编号、答案和在每个类的默认构造函数中调用的执行时间附加到文本文件中.我可以手动更改所有 50 个的函数调用,但是随着我继续完成问题,这最终会导致大量工作.

I have completed 50 problems now, and I want to create a loop to run them all. My base class Problem has a method that appends to a text file the problem number, the answer, and the execution time that's called in each class's default constructor. I could manually change the function call for all 50, but as I continue to complete problems, this will end up being a lot of work.

我更愿意以编程方式进行.我希望这个伪代码成为现实:

I'd much rather do it programatically. I was hoping for this pseudocode become a reality:

for (int i = 1; i <= 50; i++) { string statement = "Problem prob = new Problem" + i + "();"; // Execute statement }

推荐答案

通过反射,你可以做更多更好的事情.

with reflections, you can do much nicer things.

例如声明一个接口

interface IEulerProblem { void SolveProblem(); }

编写从 IEulerProblem 派生的类.

write your classes which are derived from IEulerProblem.

然后您可以在(技术上)一行漂亮的代码中运行所有内容:

then you can run all within (technically) one nice line of code:

Assembly.GetEntryAssembly() .GetTypes() .Where(t => typeof(IEulerProblem).IsAssignableFrom(t)) .Where(t => !t.IsInterface && !t.IsAbstract) .Select(t => Activator.CreateInstance(t) as IEulerProblem) .OrderBy(t => t.GetType().Name).ToList() .ForEach(p => p.SolveProblem());

更多推荐

如何使用反射或替代以编程方式创建函数调用?

本文发布于:2023-11-12 09:54:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581167.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   反射   函数   方式

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!