有没有办法可以使用字符串引用.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)); }
更多推荐
动态地创建一个< Type>对象
发布评论