创建类对象的代码看起来如何:

string myClass = "MyClass";

上面的类型,然后调用

string myMethod = "MyMethod";

在那个物体上?

有帮助吗?

解决方案

例,但没有错误检查:

using System;
using System.Reflection;

namespace Foo
{
    class Test
    {
        static void Main()
        {
            Type type = Type.GetType("Foo.MyClass");
            object instance = Activator.CreateInstance(type);
            MethodInfo method = type.GetMethod("MyMethod");
            method.Invoke(instance, null);
        }
    }

    class MyClass
    {
        public void MyMethod()
        {
            Console.WriteLine("In MyClass.MyMethod");
        }
    }
}

每个步骤需要认真检查-你不可能找到的类型,也可以不具有无参构造,你不可能找到方法,你可以调用与错误的论点类型。

有一点要注意:类型。GetType(string)需要大会审合格名称的类型,除非它是在当前正在执行的组装或mscorlib.

其他提示

我创建了一个使用 .NET 简化动态对象创建和调用的库,您可以在 google code 中下载该库和代码: 后期绑定助手在项目中你会发现 包含用法的 Wiki 页面, ,或者你也可以检查这个 代码项目中的文章

使用我的库,您的示例将如下所示:

IOperationInvoker myClass = BindingFactory.CreateObjectBinding("MyClassAssembly", "MyClass");
myClass.Method("MyMethod").Invoke();

或者甚至更短:

BindingFactory.CreateObjectBinding("MyClassAssembly", "MyClass")
     .Method("MyMethod")
     .Invoke();

它采用流畅的界面,真正简化了此类操作。我希望你会发现它很有用。

下面假设与公共构造和返回一些值,但没有参数的公共方法的对象。

var object = Activator.CreateInstance( "MyClass" );
var result = object.GetType().GetMethod( "MyMethod" ).Invoke( object, null );

假设你的类是在执行的程序集,你的构造和你的方法是无参数。

Type clazz = System.Reflection.Assembly.GetExecutingAssembly().GetType("MyClass");

System.Reflection.ConstructorInfo ci = clazz.GetConstructor(new Type[] { });
object instance = ci.Invoke(null); /* Send parameters instead of null here */

System.Reflection.MethodInfo mi = clazz.GetMethod("MyMethod");
mi.Invoke(instance, null); /* Send parameters instead of null here */
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top