如何做到动态对象的创建和方法调用的.NET 3.5 [英] How to do dynamic object creation and method invocation in .NET 3.5
本文介绍了如何做到动态对象的创建和方法调用的.NET 3.5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在code相,将创建类的一个对象:
How does the code looks that would create an object of class:
string myClass = "MyClass";
上述类型,然后调用
Of the above type, and then call
string myMethod = "MyMethod";
在该对象?
推荐答案
- 使用<一个href="http://msdn.microsoft.com/en-us/library/system.type.gettype.aspx"><$c$c>Type.GetType(string)$c$c>获得类型的对象。
- 使用<一个href="http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx"><$c$c>Activator.CreateInstance(Type)$c$c>创建一个实例。
- 使用<一个href="http://msdn.microsoft.com/en-us/library/system.type.getmethod.aspx"><$c$c>Type.GetMethod(string)$c$c>检索的方法。
- 使用<一个href="http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.invoke.aspx"><$c$c>MethodBase.Invoke(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(串)需要的类型的程序集限定名称,除非它是在当前执行的程序集或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屋!
查看全文