是否有一种方法可以基于我在运行时知道类的名称这一事实来创建类的实例。基本上,我将类名放在字符串中。
当前回答
这很简单。假设您的类名是Car,名称空间是Vehicles,然后将参数传递为Vehicles。返回Car类型的对象。像这样,您可以动态地创建任何类的任何实例。
public object GetInstance(string strFullyQualifiedName)
{
Type t = Type.GetType(strFullyQualifiedName);
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;
}
现在,如果你想调用一个参数化构造函数,请执行以下操作
Activator.CreateInstance(t,17); // Incase you are calling a constructor of int type
而不是
Activator.CreateInstance(t);
其他回答
看看激活器。CreateInstance除外的方法。
要从解决方案中的另一个项目中创建类的实例,您可以获得由任何类的名称指示的程序集(例如BaseEntity)并创建一个新实例:
var newClass = System.Reflection.Assembly.GetAssembly(typeof(BaseEntity)).CreateInstance("MyProject.Entities.User");
ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));
你为什么要写这样的代码?如果你有一个'ReportClass'类可用,你可以直接实例化它,如下所示。
ReportClass report = new ReportClass();
代码ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(ReportClass));当没有必要的类可用,但想动态实例化和或或调用方法时使用。
我的意思是,当你知道程序集,但在写代码时,你没有类ReportClass可用时,它是有用的。
这很简单。假设您的类名是Car,名称空间是Vehicles,然后将参数传递为Vehicles。返回Car类型的对象。像这样,您可以动态地创建任何类的任何实例。
public object GetInstance(string strFullyQualifiedName)
{
Type t = Type.GetType(strFullyQualifiedName);
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;
}
现在,如果你想调用一个参数化构造函数,请执行以下操作
Activator.CreateInstance(t,17); // Incase you are calling a constructor of int type
而不是
Activator.CreateInstance(t);
我曾经成功地使用过这个方法:
System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)
您需要将返回的对象强制转换为所需的对象类型。
推荐文章
- 静态隐式运算符
- 不区分大小写列表搜索
- 'throw'和'throw new Exception()'的区别
- 不能在lambda表达式中使用ref或out参数
- c# int到字节[]
- 如何跟踪log4net问题
- 将WPF组合框绑定到自定义列表
- foreach vs somlist . foreach (){}
- 为什么try{…}最后{…}好;尝试{…} catch{}坏?
- c# 8用多种情况切换表达式,结果相同
- 在没有事件源注册的情况下写入Windows应用程序事件日志
- 并发HashSet<T>在。net框架?
- 从控制器内获得控制器和动作名称?
- _ViewStart的位置和方式。CSHTML布局文件链接?
- 新建T()