Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在.NET3.5中创建动态对象和调用方法_C#_.net_Dynamic_Clr_Invocation - Fatal编程技术网

C# 如何在.NET3.5中创建动态对象和调用方法

C# 如何在.NET3.5中创建动态对象和调用方法,c#,.net,dynamic,clr,invocation,C#,.net,Dynamic,Clr,Invocation,创建类对象的代码外观如何: string myClass = "MyClass"; ,然后调用 string myMethod = "MyMethod"; 在那个物体上? 用于获取类型对象 用于创建实例 用于检索方法 用于调用对象上的方法 示例,但没有错误检查: using System; using System.Reflection; namespace Foo { class Test { static void Main() {

创建类对象的代码外观如何:

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");
        }
    }
}
每个步骤都需要仔细检查-可能找不到类型,可能没有无参数构造函数,可能找不到方法,可能使用错误的参数类型调用它


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

以下假定对象具有公共构造函数和公共方法,该方法返回一些值但不带参数

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 */

我创建了一个库,它使用.NET简化了动态对象的创建和调用。您可以在google代码中下载该库和代码: 在项目中,您将找到一个,或者您也可以检查这个

使用my library,您的示例如下所示:

IOperationInvoker myClass = BindingFactory.CreateObjectBinding("MyClassAssembly", "MyClass");
myClass.Method("MyMethod").Invoke();
甚至更短:

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

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

我想你需要澄清你的问题。您是否正在尝试动态创建该类型,即动态定义一个类,以及对该类型动态调用一个方法?