Pet*_*teT 198 .net c# instantiation system.type
有没有办法根据我在运行时知道类的名称来创建类的实例.基本上我会在字符串中有类的名称.
Mat*_*ton 150
看一下Activator.CreateInstance方法.
Sar*_*avu 63
它非常简单.假设您的类名是Car和命名空间Vehicles,然后传递Vehicles.Car返回类型对象的参数Car.像这样,您可以动态创建任何类的任何实例.
public object GetInstance(string strFullyQualifiedName)
{
Type t = Type.GetType(strFullyQualifiedName);
return Activator.CreateInstance(t);
}
Run Code Online (Sandbox Code Playgroud)
如果您的完全限定名称(即,Vehicles.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;
}
Run Code Online (Sandbox Code Playgroud)
现在,如果要调用参数化构造函数,请执行以下操作
Activator.CreateInstance(t,17); // Incase you are calling a constructor of int type
Run Code Online (Sandbox Code Playgroud)
代替
Activator.CreateInstance(t);
Run Code Online (Sandbox Code Playgroud)
Ray*_* Li 53
我成功地使用了这个方法:
System.Reflection.Assembly.GetExecutingAssembly().CreateInstance(string className)
Run Code Online (Sandbox Code Playgroud)
您需要将返回的对象强制转换为所需的对象类型.
Pet*_*teT 22
可能我的问题应该更加具体.我实际上知道字符串的基类,所以解决了它:
ReportClass report = (ReportClass)Activator.CreateInstance(Type.GetType(reportClass));
Run Code Online (Sandbox Code Playgroud)
Activator.CreateInstance类有各种方法以不同的方式实现相同的功能.我可以将它投射到一个物体,但上面对我的情况最有用.
要从解决方案中的另一个项目创建类的实例,您可以获取由任何类的名称(例如 BaseEntity)指示的程序集并创建一个新实例:
var newClass = System.Reflection.Assembly.GetAssembly(typeof(BaseEntity)).CreateInstance("MyProject.Entities.User");
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
247927 次 |
| 最近记录: |