如何在.NET 3.5中进行动态对象创建和方法调用

thr*_*thr 2 .net c# clr dynamic invocation

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

string myClass = "MyClass";
Run Code Online (Sandbox Code Playgroud)

以上类型,然后调用

string myMethod = "MyMethod";
Run Code Online (Sandbox Code Playgroud)

那个对象?

Jon*_*eet 10

示例,但没有错误检查:

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");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

每一步都需要仔细检查 - 你可能找不到类型,它可能没有无参数构造函数,你可能找不到方法,你可能用错误的参数类型调用它.

有一点需要注意:Type.GetType(string)需要类型的程序集限定名称,除非它在当前正在执行的程序集或mscorlib中.