2009-07-13 50 views

回答

26

你将要使用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"); 
    } 
} 

现在,这是一个非常简单的例子,没有错误检查,如果类型住在另一个组件,但我认为也忽略了喜欢做什么更大的问题这应该让你在正确的轨道上。

+0

只要程序集加载并且typename是装配限定的,您就是金。 – 2009-07-13 15:52:32

+0

嗯......我',找到你的例子返回null在“Type.GetType(myclass);” – pistacchio 2009-07-13 15:52:58

8

事情是这样的:

public object InvokeByName(string typeName, string methodName) 
{ 
    Type callType = Type.GetType(typeName); 

    return callType.InvokeMember(methodName, 
        BindingFlags.InvokeMethod | BindingFlags.Public, 
        null, null, null); 
} 

你应该根据你想打电话,以及检查Type.InvokeMember方法在MSDN中是一定的你真正需要的方法修改绑定标志。

-3

你这样做的理由是什么?更可能的是,您可以在没有反射的情况下执行此操作,直至并包括动态组装加载。