从类名创建实例 [英] Creating an instance from a class name

查看:28
本文介绍了从类名创建实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在运行时创建一个类的实例.我试图创建的所有类都继承自基类 ConfigMgrObj,并命名为 ConfigMgr_xxxxxx 例如ConfigMgr_Collection.它们都采用一个我称之为 oController 的特殊对象和一个字符串作为参数.

I'm trying to create an instance of a class at run time. The classes I'm trying to create all inherit from a base class, ConfigMgrObj, and are named ConfigMgr_xxxxxx e.g. ConfigMgr_Collection. They all take a special object that I'm calling oController and a string as arguments.

这是我用来做的行,其中 ClassToGet 是一个包含类名的字符串,例如ConfigMgr_Collection.

This is the line I'm using to do it, where ClassToGet is a string that contains the name of the class e.g. ConfigMgr_Collection.

object oNewObject = System.Activator.CreateInstance(null, "StackOverflowNamespace." + ClassToGet, new object[] { oController, ClassToGet });

这会引发 TypeLoadException 异常.怎么回事?

This throws a TypeLoadException exception. What's up with it?

推荐答案

您尝试实例化的类型是否在同一个程序集中实际声明?传递 null 作为第一个参数是告诉 Activator 这些类型存在于当前程序集中.

Are the types you're trying to instantiate actually declared within the same assembly? Passing null as the first parameter is telling Activator that the types live in the current assembly.

这篇关于从类名创建实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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