动态地创建一个< Type>对象

编程入门 行业动态 更新时间:2024-10-26 02:35:27
本文介绍了动态地创建一个< Type>对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我的数据库中有一个表,用于管理我的应用程序中的关系。它的本质是非常基本的 - parentType,parentId,childType,childId ... all作为int。我以前做过这个设置,但是当我有6个不同的表,我试图链接时,我用一个开关/案例设置。现在我有30个表,我试图这样做,我想能够做到这一点,而不必在我的切换命令中写入30个条目。

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

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

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

解决方案

此链接应该有助于:

msdn.microsoft/ 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:

msdn.microsoft/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;对象

本文发布于:2023-11-09 06:12:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571601.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:创建一个   对象   动态   gt   lt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!