简体   繁体   中英

Execute a function from a variable in C#

Is there any way so that you can call a function with a variable?

variable+"()";

or something like that, or would I have to use if statements?

A switch seems like it might be the answer, so if the variable's value=var1 I want it to execute var1(); if the value is var2 I want it to execute var2(); how would I code it?

Basically, I am trying to find a cleaner alternative to

if (variable == var1)
{
var1();
}
if (variable == var2)
{
var2();
}

It would be possible to use reflection to find a method in an object and call that method, but the simplest and fastest would be to simply use a switch:

switch (variable) {
  case "OneMethod": OneMethod(); break;
  case "OtherMethod": OtherMethod(); break;
}

You could use Reflection http://msdn.microsoft.com/en-us/library/ms173183(v=vs.80).aspx to access any function or member by name. It takes some getting used to though. It also has performance issues, so if you can avoid using it, you should.

This is what delegates are for:

Action f = ()=>Console.WriteLine("foo");
f();

I assume using strings is not actually a requirement.

You can use delegates. MSDN: http://msdn.microsoft.com/en-us/library/900fyy8e(v=vs.71).aspx Exa:

public delegate void TestDelegate();

class TestDelegate
{
        public static void Test()
        {
                Console.WriteLine("In Test");
        }

        public static void Main()
        {
                TestDelegate testDelegate = new TestDelegate(Test);

                testDelegate();
        }
}

You can use the MethodInfo class

Type yourtype = yourObject.GetType();

MethodInfo method = yourtype.GetMethod(variable);
var result = method.Invoke(yourObject,null);
string className = "My.Program.CoolClass"; //including namespace
string method= "Execute";
var type = Type.GetType(className);
var method = type.GetMethod(method);
method.Invoke(classObj, null);

Here's a sample how you can call a method via reflection :

public class MyClass
{
    public void PrintHello()
    {
        Console.WriteLine("Hello World");
    }
}

//...

public void InvokeMethod(object obj, string method)
{
  // call the method
  obj.GetType().GetMethod(method).Invoke(obj, null);
}

//...
var o = new MyClass();
var method = "PrintHello";
//...
InvokeMethod(o, method);

(I will complete @Matthew's excellent answer):

var x =  (Action) ( ()=>Print("foo") );    
x(); 

ps you can fully variable names too:

private Dictionary<string, dynamic> my =  new Dictionary<string, dynamic>();
my["x"]  = .....
my["x"]();
public class FunctionTest
{

    void Main()
    {
        Action doSomething;

        doSomething = FirstFunction;
        doSomething();

        doSomething = SecondFunction;
        doSomething();
    }

    void FirstFunction()
    {
        Console.Write("Hello, ");
    }

    void SecondFunction()
    {
        Console.Write("World!\n");
    }
}

output:

Hello, World!

Doesn't get too much simpler than that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM