代码之家  ›  专栏  ›  技术社区  ›  pistacchio

如何在.NET中动态调用类的方法?

  •  13
  • pistacchio  · 技术社区  · 16 年前

    如何将类和方法名作为 并调用该类的方法?

    喜欢

    void caller(string myclass, string mymethod){
        // call myclass.mymethod();
    }
    

    谢谢

    3 回复  |  直到 16 年前
        1
  •  30
  •   Andrew Hare    16 年前

    你会想用的 reflection .

    下面是一个简单的例子:

    using System;
    using System.Reflection;
    
    class Program
    {
        static void Main()
        {
            caller("Foo", "Bar");
        }
    
        static void caller(String myclass, String mymethod)
        {
            // Get a type from the string 
            Type type = Type.GetType(myclass);
            // Create an instance of that type
            Object obj = Activator.CreateInstance(type);
            // Retrieve the method you are looking for
            MethodInfo methodInfo = type.GetMethod(mymethod);
            // Invoke the method on the instance we created above
            methodInfo.Invoke(obj, null);
        }
    }
    
    class Foo
    {
        public void Bar()
        {
            Console.WriteLine("Bar");
        }
    }
    

    现在这是一个 非常 简单的例子,没有错误检查,也忽略了更大的问题,比如如果类型存在于另一个程序集中,该怎么做,但是我认为这会使您走上正确的道路。

        2
  •  8
  •   Fabrício Matté    16 年前

    像这样:

    public object InvokeByName(string typeName, string methodName)
    {
        Type callType = Type.GetType(typeName);
    
        return callType.InvokeMember(methodName, 
                        BindingFlags.InvokeMethod | BindingFlags.Public, 
                        null, null, null);
    }
    

    您应该根据您想要调用的方法修改绑定标志,并检查msdn中的type.invokemember方法以确定您真正需要什么。

        3
  •  -3
  •   clemahieu    16 年前

    你为什么这么做?很可能您可以在没有反射的情况下进行此操作,直到并包括动态装配加载。