【问题标题】:How to call public functions dynamically at run time如何在运行时动态调用公共函数
【发布时间】:2012-01-21 21:46:18
【问题描述】:

我想在运行时按它们的名字来调用函数,比如

string srFunctionName="MyFunction";

所以使用这个变量我想调用名为“MyFunction”的函数。我该怎么做?

【问题讨论】:

    标签: c# wpf function dynamic call


    【解决方案1】:

    你可以使用Reflection:

    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
    );
    

    更新:

    根据 cmets 部分的要求,这里有一个具有实际功能的完整示例:

    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);
            }
        }
    }
    

    【讨论】:

    • 你好。感谢您的回答。你能举一个完整的例子,包括一些基本的实际功能。这真的很令人困惑。我还将 HtmlDocument 变量作为参数传递给函数。 HtmlDocument 是 htmlagilitypack 的对象。
    • @MonsterMMORPG,当然,我已经包含了一个完整的例子。请查看我的更新答案。
    【解决方案2】:

    这里是一个关闭form的例子

    object instance = form;
    Type myType = form.GetType();
    
    myType.InvokeMember("Close", BindingFlags.InvokeMethod, null, instance, null);
    

    【讨论】:

      【解决方案3】:

      您可以使用反射来创建类的对象,然后使用该对象调用函数。

          object Instance = Activator.CreateInstance(t); // t is type
          MethodInfo mi = t.GetMethod(srFunctionName); 
          if (mi != null)
                  mi.Invoke(Instance, args);
          else
                 logError();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-24
        • 2015-07-08
        相关资源
        最近更新 更多