在编译时可能并不总是知道对象的类型,但可能需要创建该类型的实例。
如何从类型中获得一个新的对象实例?
在编译时可能并不总是知道对象的类型,但可能需要创建该类型的实例。
如何从类型中获得一个新的对象实例?
当前回答
这很简单。假设您的类名是Car,名称空间是Vehicles,然后将参数传递为Vehicles。返回Car类型的对象。像这样,您可以动态地创建任何类的任何实例。
public object GetInstance(string strNamesapace)
{
Type t = Type.GetType(strNamesapace);
return Activator.CreateInstance(t);
}
如果您的完全限定名称(即车辆。在本例中,Car)位于另一个组件Type中。GetType将为null。在这种情况下,您必须遍历所有程序集并找到Type。为此,可以使用下面的代码
public object GetInstance(string strFullyQualifiedName)
{
Type type = Type.GetType(strFullyQualifiedName);
if (type != null)
return Activator.CreateInstance(type);
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
type = asm.GetType(strFullyQualifiedName);
if (type != null)
return Activator.CreateInstance(type);
}
return null;
}
您可以通过调用上面的方法来获取实例。
object objClassInstance = GetInstance("Vehicles.Car");
其他回答
答案已经给出了:
ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);
然而,Activator类有一个无参数构造函数的泛型变体,通过使强制转换变得不必要,并且不需要传递对象的运行时类型,使其更具可读性:
ObjectType instance = Activator.CreateInstance<ObjectType>();
这很简单。假设您的类名是Car,名称空间是Vehicles,然后将参数传递为Vehicles。返回Car类型的对象。像这样,您可以动态地创建任何类的任何实例。
public object GetInstance(string strNamesapace)
{
Type t = Type.GetType(strNamesapace);
return Activator.CreateInstance(t);
}
如果您的完全限定名称(即车辆。在本例中,Car)位于另一个组件Type中。GetType将为null。在这种情况下,您必须遍历所有程序集并找到Type。为此,可以使用下面的代码
public object GetInstance(string strFullyQualifiedName)
{
Type type = Type.GetType(strFullyQualifiedName);
if (type != null)
return Activator.CreateInstance(type);
foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
{
type = asm.GetType(strFullyQualifiedName);
if (type != null)
return Activator.CreateInstance(type);
}
return null;
}
您可以通过调用上面的方法来获取实例。
object objClassInstance = GetInstance("Vehicles.Car");
泛型T T = new T();工作吗?
根系统名称空间中的Activator类非常强大。
有很多重载用于将参数传递给构造函数等。请在以下地址查看文档:
http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx
或者(新路径)
https://learn.microsoft.com/en-us/dotnet/api/system.activator.createinstance
这里有一些简单的例子:
ObjectType instance = (ObjectType)Activator.CreateInstance(objectType);
ObjectType instance = (ObjectType)Activator.CreateInstance("MyAssembly","MyNamespace.ObjectType");
不使用反射:
private T Create<T>() where T : class, new()
{
return new T();
}