可以将字符串转换为方法吗? [英] Possible to convert a string into a method?

查看:63
本文介绍了可以将字符串转换为方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何使用变量并将其像方法一样使用?我听到了一些有关方法调用的信息,但是找不到任何好的方法.如果有人可以编辑此代码并使之生效,请呢?

How would I take a variable and use it like a method? I heard something about method invoking but I can''t find anything good about it. If someone could just edit this code and make it work please?

namespace test
{
    static class Program
    {
        public void Main()
        {
            time(0, "command1");
            time(5000, "command2");
        }

        public void command1(object source, ElapsedEventArgs e)
        {
            MessageBox.Show("command1, prepair for 5 second gap!");
        }

        public void command2(object source, ElapsedEventArgs e)
        {
            MessageBox.Show("command2, gap complete!");
        }

        public void time(int value, string choice)
        {
            System.Timers.Timer t = new System.Timers.Timer();
            t.Elapsed += new ElapsedEventHandler(choice);
            t.Interval = value;
            t.AutoReset = false;
            t.Start();
        }
    }
}




感谢您的帮助.




Thanks for any help.

推荐答案

您可以轻松地做到这一点,但您不应该这样做.想象有人重命名该方法,即使编译了该系统,您的所有系统也会被破坏.

相反,您应该创建一个接口.使用反射,列出您需要查找程序集的所有类,以找到实现其接口的类.找到(如果找到)该类时,找到其构造函数并调用它(通过System.Reflection.ConstructorInfo).您获得了实现接口的class实例(类型为System.Object的变量).将此对象键入强制类型转换到您的界面.您获得了对接口类型的对象实例的引用.调用方法之一.完成了!

带接口的方法既安全又好用,因为如果有人只在一个地方对其进行重命名或以任何不兼容的方式对其进行更改,编译器就会立即向您展示如何解决该问题.

—SA
You can do it easily, but you should not. Imagine somebody rename the method and all you system will be destroyed, even though it compiles.

Instead, you should create an interface. With Reflection, list all classes of the Assembly you need to find the class which implement its interface. When (and if) the class is found, find its constructor and invoke it (through System.Reflection.ConstructorInfo). You got the instance of class (the variable of the type System.Object) implementing your interface. Type cast this object to your interface. You got the reference to your object instance of the interface type. Call one the methods. You''re done!

The method with interface is good and safe, because if anyone renames it in just one place or change it any incompatible way, compiler will immediately show you how to fix the problem.

—SA


可以做这种事情,但我不建议这样做.如果您需要这样做,那么您的设计可能是错误的.

查看运行时代码生成I:使用Microsoft.CSharp和System.CodeCom编译C#代码.编译器 [ ^ ]到看看它是否符合您的要求.
That sort of thing can be done, but I would not recommend it. If you need to do this then your design is probably wrong.

Take a look at Run-Time Code Generation I: Compile C#-Code using Microsoft.CSharp and System.CodeCom.Compiler[^] to see if it fits your requirements.


这篇关于可以将字符串转换为方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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