C# 动态创建 <Type> 的对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/578495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Dynamically create an object of <Type>
提问by thaBadDawg
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.
我的数据库中有一个表,用于管理应用程序中的关系。它本质上是非常基本的 - parentType、parentId、childType、childId ......所有这些都是整数。我以前做过这个设置,但是当我有 6 个不同的表试图链接时,我用 switch/case 设置做了它。现在我有 30 个表,我想用它来做这件事,我希望能够做到这一点,而不必在我的 switch 命令中写入 30 个案例条目。
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):
有没有办法可以使用字符串引用 .Net 类?我知道这是无效的(因为我已经尝试了几种变体):
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?
我知道如何获取对象的类型,但如何使用它来创建新对象?
采纳答案by Jason Miesionczek
This link should help:
这个链接应该有帮助:
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 will create an instance of the specified type.
Activator.CreateInstance 将创建一个指定类型的实例。
you could wrap that in a generic method like this:
您可以将其包装在这样的通用方法中:
public T GetInstance<T>(string type)
{
return (T)Activator.CreateInstance(Type.GetType(type));
}
回答by Andrew Hare
You want to use Activator.CreateInstance
.
Here is an example of how it works:
以下是它如何工作的示例:
using System;
using System.Runtime.Remoting;
class Program
{
static void Main()
{
ObjectHandle o = Activator.CreateInstance("mscorlib.dll", "System.Int32");
Int32 i = (Int32)o.Unwrap();
}
}
回答by Judah Gabriel Himango
If the type is known by the caller, there's a better, faster way than using Activator.CreateInstance: you can instead use a generic constraint on the method that specifies it has a default parameterless constructor.
如果调用者知道该类型,则有一种比使用 Activator.CreateInstance 更好、更快的方法:您可以改为对指定它具有默认无参数构造函数的方法使用通用约束。
Doing it this way is type-safe and doesn't require reflection.
这样做是类型安全的,不需要反射。
T CreateType<T>() where T : new()
{
return new T();
}
回答by sduplooy
Assuming you have the following type:
假设您有以下类型:
public class Counter<T>
{
public T Value { get; set; }
}
and have the assembly qualified name of the type, you can construct it in the following manner:
并具有类型的程序集限定名称,您可以按以下方式构造它:
string typeName = typeof(Counter<>).AssemblyQualifiedName;
Type t = Type.GetType(typeName);
Counter<int> counter =
(Counter<int>)Activator.CreateInstance(
t.MakeGenericType(typeof(int)));
counter.Value++;
Console.WriteLine(counter.Value);
回答by AmuuuInjured
public static T GetInstance<T>(params object[] args)
{
return (T)Activator.CreateInstance(typeof(T), args);
}
I would use Activator.CreateInstance()instead of casting, as the Activator has a constructor for generics.
我会使用Activator.CreateInstance()而不是强制转换,因为 Activator 有一个泛型构造函数。
回答by Assaf S.
Here is a function I wrote that clones a record of type T, using reflection. This is a very simple implementation, I did not handle complex types etc.
这是我编写的一个函数,它使用反射克隆 T 类型的记录。这是一个非常简单的实现,我没有处理复杂的类型等。
public static T Clone<T>(T original)
{
T newObject = (T)Activator.CreateInstance(original.GetType());
foreach (var prop in original.GetType().GetProperties())
{
prop.SetValue(newObject, prop.GetValue(original));
}
return newObject;
}
I hope this can help someone.
我希望这可以帮助某人。
Assaf
阿萨夫