动态地创建一个< Type>对象 [英] Dynamically create an object of <Type>

查看:97
本文介绍了动态地创建一个< Type>对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据库中有一个表,用于管理我的应用程序中的关系。它的本质是非常基本的 - parentType,parentId,childType,childId ... all作为int。我以前做过这个设置,但是当我有6个不同的表,我试图链接时,我用一个开关/案例设置。现在我有30个表,我试图这样做,我想能够做到这一点,而不必在我的切换命令中写入30个条目。



有没有办法可以使用字符串引用.NET类?我知道这是无效的(因为我已经尝试了几种变体):

 类型t​​ = Type.GetType WebCore.Models.Page); 
object page = new t();

我知道如何获取对象的类型,但是如何在飞行中使用它创建一个新对象?

解决方案

此链接应该有助于:



http://msdn.microsoft.com/ en-us / library / system.activator.createinstance(VS.71).aspx



Activator.CreateInstance将创建一个指定类型的实例。 / p>

你可以用这样的通用方法来包装:

  public T GetInstance< T>(string type)
{
return(T)Activator.CreateInstance(Type.GetType(type));
}


I have a table in my database that I use to manage relationships across my application. it's pretty basic in it's nature - parentType,parentId, childType, childId... all as ints. I've done this setup before, but I did it with a switch/case setup when I had 6 different tables I was trying to link. Now I have 30 tables that I'm trying to do this with and I would like to be able to do this without having to write 30 case entries in my switch command.

Is there a way that I can make reference to a .Net class using a string? I know this isn't valid (because I've tried several variations of this):

Type t = Type.GetType("WebCore.Models.Page");
object page = new t();

I know how to get the Type of an object, but how do I use that on the fly to create a new object?

解决方案

This link should help:

http://msdn.microsoft.com/en-us/library/system.activator.createinstance(VS.71).aspx

Activator.CreateInstance will create an instance of the specified type.

you could wrap that in a generic method like this:

public T GetInstance<T>(string type)
{
    return (T)Activator.CreateInstance(Type.GetType(type));
}

这篇关于动态地创建一个&lt; Type&gt;对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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