如何使用c#从String调用方法?

时间:2012-07-26 14:57:56

标签: c#

我创建了一个类库,它有4个类,每个类有1个方法。 第一堂课是我的主要课程,在我的第一堂课中,我有一个名为calltoaction的字符串,在这个字符串中我将动态获得以下列表之一

  1. class2.Method2()
  2. class3.Method3()
  3. class4.Method4()
  4. 现在我想从字符串“calltoaction”执行“class2.method2”。

    说出来:

    class Class1
    {
        public void method1()
        {
            string calltoaction = "Class2.Method2()";
        }
    }
    

    如何从字符串中执行“Class2.Method”?

3 个答案:

答案 0 :(得分:4)

我不完全确定你想要完成什么,但我相信它可以以更好的方式完成。基本上,如果我正确理解你的问题,调用这个函数会返回你想要执行的类和方法的名称。

如果是这种情况,我会无限期地放弃整个“字符串”,并开始查看代表。

考虑一下:

public class Class2
{
    public static void Method2() { } 
} // eo class 2

public class Class3
{
    public static void Method3() { } 
} // eo class 3

public class Class4
{
    public static void Method4() { } 
} // eo class 4

现在我们来到我们的主要班级

public class MainClass
{
    private delegate void MethodDelegate();
    private List<MethodDelegate> delegates_ = new List<MethodDelegate>();

    // ctor
    public MainClass()
    {
        delegates_.Add(Class2.Method2);
        delegates_.Add(Class3.Method3);
        delegates_.Add(Class4.Method4);
    }

    // Call a method
    public void Method1()
    {
        // decide what you want to call:
        delegates_[0].Invoke(); // "Class2.Method2"
    } // eo Method1
}  // eo class Main

答案 1 :(得分:1)

我认为一种低技术方式是使用这样的开关语句:

using System;

namespace ConsoleApplication24
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Which method would you like to run?");
            RunMyMethod(Console.ReadLine());
        }

        private static void RunMyMethod(string p)
        {
            switch (p)
            {
                case "MethodOne();":
                    MethodOne();
                    break;
                case "MethodTwo();":
                    MethodTwo();
                    break;
                case "MethodThree();":
                    MethodThree();
                    break;
            }
        }

        private static void MethodThree()
        {
            //Do Stuff
        }

        private static void MethodTwo()
        {
            //Do Stuff
        }

        private static void MethodOne()
        {
            //Do Stuff
        }
    }
}

答案 2 :(得分:1)

使用Action代替字符串(假设您不需要返回值。如果您这样做 - 使用Func):

这是关于如何使用它的想法:

public Form1()
{
    InitializeComponent();

    Action<string> calltoaction;
    calltoaction = Doit;
    calltoaction("MyText1");
    calltoaction = Doit2;
    calltoaction("MyText2");
}

void Doit(string s)
{ Text = s; }

void Doit2(string s)
{ textBox1.Text = s; }