如何在.NET 3.5中进行动态对象创建和方法调用 [英] How to do dynamic object creation and method invocation in .NET 3.5

查看:355
本文介绍了如何在.NET 3.5中进行动态对象创建和方法调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码如何创建一个类的对象:

How does the code looks that would create an object of class:

string myClass = "MyClass";

上述类型中,然后调用

string myMethod = "MyMethod";

在该对象上

推荐答案


  • 使用 Type.GetType(string) 以获取类型对象。

  • 使用 Activator.CreateInstance(Type) 创建一个实例。

  • 使用 Type.GetMethod(string) 来检索方法。

  • 使用 MethodBase.Invoke(object,object []) 来调用对象的方法

    • Use Type.GetType(string) to get the type object.
    • Use Activator.CreateInstance(Type) to create an instance.
    • Use Type.GetMethod(string) to retrieve a method.
    • Use MethodBase.Invoke(object, object[]) to invoke the method on the object
    • 示例,但不检查错误:

      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");
              }
          }
      }
      

      每一步需要仔细检查 - 您可能找不到该类型,它可能没有无参数的构造函数,您可能找不到该方法,您可以使用错误的参数类型来调用它。

      Each step needs careful checking - you may not find the type, it may not have a parameterless constructor, you may not find the method, you may invoke it with the wrong argument types.

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

      One thing to note: Type.GetType(string) needs the assembly-qualified name of the type unless it's in the currently executing assembly or mscorlib.

      这篇关于如何在.NET 3.5中进行动态对象创建和方法调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆