动态创建℃的对象;类型> [英] Dynamically create an object of <Type>

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

问题描述

我在我的数据库中的表,我用它来管理在我的应用程序的关系。这是pretty的基础,在它的本质 - ParentType的,parentId的,childType,childId ......都为整数。我以前做过这样的设置,但我没有用一个开关/箱的设置,当我有6个不同的表,我试图联系。现在我有30桌,我试着用做到这一点,我想是能够做到这一点,而无需编写30项的情况下在我的切换命令。

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.

有没有一种方法,我可以参考使用字符串的.NET类?我知道这是无效的(因为我已经试过这几种变体):

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?

推荐答案

这个链接应该帮助:

<一个href="http://msdn.microsoft.com/en-us/library/system.activator.createinstance(VS.71).aspx">http://msdn.microsoft.com/en-us/library/system.activator.createinstance(VS.71).aspx

Activator.CreateInstance将创建指定类型的实例。

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

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

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