字符串值变量

Zeb*_*man 1 c# reflection

这是场景

string dataTypeName = "Employee";
Run Code Online (Sandbox Code Playgroud)

Employee是哪个类,我想创建它的对象.

Type EmployeeObject = Type.GetType(dataTypeName);
Run Code Online (Sandbox Code Playgroud)

现在我想像这样实例化Employee的对象

EmployeeObject emp1 = new Employee();
Run Code Online (Sandbox Code Playgroud)

可能吗.但是这种方法不起作用.我对反思没有强烈的想法.请指导我.

Nah*_*hum 5

CreateObjectfromassemblynameandclassname

using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;


public class Reflection
{

    public static T CreateObject<T>(string assemblyName, string className)
    {
        Assembly assembly = Assembly.Load(assemblyName);
        return (T)assembly.CreateInstance(className);
    }
}
Run Code Online (Sandbox Code Playgroud)