2013-05-28 80 views
1

下面是场景
字符串值设置为可变

string dataTypeName = "Employee"; 

其中员工是一流的,我想利用它的对象。

Type EmployeeObject = Type.GetType(dataTypeName); 

现在我想实例化员工的目标是这样

EmployeeObject emp1 = new Employee(); 

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

+0

什么是价值 - 'typeof运算(员工).AssemblyQualifiedName'?什么是需要从名称中获得'EmployeeObject',然后用字面类型将其反过来 - 为什么不首先使用字面类型呢? – LukeHennerley

+0

@LukeHennerley Value:Reflection.Employee,Reflection,Version = 1.0.0.0,Culture = neutral,PublicKeyToken = null –

+0

http://stackoverflow.com/questions/752/get-a-new-object-instance-from-a -类型 – Freelancer

回答

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); 
    } 
}