Как динамически вызывать публичные функции во время выполнения - PullRequest
0 голосов
/ 22 января 2012

Я хочу вызывать функции по их имени во время выполнения, как

string srFunctionName="MyFunction";

Так что с помощью этой переменной я хочу вызвать функцию с именем "MyFunction".Как я могу это сделать?

Ответы [ 3 ]

3 голосов
/ 22 января 2012

Вы можете использовать Отражение :

string strFunctionName = "MyFunction";

// get the type containing the method
Type t = Type.GetType("Foo.Bar.SomeTypeContainingYourFunction");

// you will need an instance of the type if the method you are
// trying to invoke is not static. If it is static you could leave that null
object instance = Activator.CreateInstance(t);

// the arguments that your method expects
new object[] arguments = new object[] { 1, "foo", false };

// invoke the method
object result = t.InvokeMember(
    strFunctionName, 
    BindingFlags.InvokeMethod, 
    null, 
    instance, 
    arguments
);

UPDATE:

В соответствии с запросом в разделе комментариев приведен полный пример с реальными функциями:

using System;
using System.Reflection;

namespace Foo.Bar
{
    public class SomeTypeContainingYourFunction
    {
        public string MyFunction(int foo, string bar, bool baz)
        {
            return string.Format("foo: {0}, bar: {1}, baz: {2}", foo, bar, baz);
        }
    }
}

namespace Bazinga
{
    class Program
    {
        static void Main()
        {
            var strFunctionName = "MyFunction";
            var t = Type.GetType("Foo.Bar.SomeTypeContainingYourFunction");
            var instance = Activator.CreateInstance(t);
            var arguments = new object[] { 1, "foo", false };
            var result = t.InvokeMember(
                strFunctionName, 
                BindingFlags.InvokeMethod, 
                null, 
                instance, 
                arguments
            );
            Console.WriteLine(result);
        }
    }
}
1 голос
/ 22 января 2012

Вы можете использовать отражение, чтобы создать объект класса, а затем вызвать функцию, используя этот объект.

    object Instance = Activator.CreateInstance(t); // t is type
    MethodInfo mi = t.GetMethod(srFunctionName); 
    if (mi != null)
            mi.Invoke(Instance, args);
    else
           logError();
1 голос
/ 22 января 2012

Вот пример, чтобы закрыть a form

object instance = form;
Type myType = form.GetType();

myType.InvokeMember("Close", BindingFlags.InvokeMethod, null, instance, null);
...