NET中按名称字符串初始化类型 [英] Initialize Type by name string in .net

查看:51
本文介绍了NET中按名称字符串初始化类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,该应用程序在启动时会从App.config中读取其设置.该应用程序可以使用其他持久性存储提供程序.目前,我已经实现了两个:Oracle和Dummy(出于测试目的).

I have an application that reads its setting at startup from App.config. The application may use different presistent storage providers. Currently I have two implemented: Oracle and Dummy (for test purposes).

现在在我的Program.cs中,我读取了要使用的存储类型的名称.它可以是OracleStorage或DemoStorage.这些是类型名称,其实现位于单独的dll项目中.

Now in my Program.cs I read the name of the type of storage to use. It may be either OracleStorage or DemoStorage. These are type names, the implementations of which reside in a separate dll project.

现在,考虑到我拥有类型名称,如何实例化一个对象?

Now, how do I instantiate an object given that I have a type name?

所以我可以写:

IStorageProvider storage = new typof(myStorageClassNameReadFromAppConfig);

推荐答案

您可以使用 Activator.CreateInstance

You can use Activator.CreateInstance combined with Type.GetType:

IStorageProvider storage = 
        (IStorageProvider) Activator.CreateInstance(
                             Type.GetType(myStorageClassNameReadFromAppConfig)
                           );

这篇关于NET中按名称字符串初始化类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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