如何使用反射或替代以编程方式创建函数调用? [英] How can I use reflection or alternative to create function calls programatically?

查看:51
本文介绍了如何使用反射或替代以编程方式创建函数调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

这篇关于如何使用反射或替代以编程方式创建函数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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