在做項目中碰到一個問題,就是如何在知道一個類的名字,如何創建這個類呢。做的一個小測試,直接貼代碼了。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ReflectFromStringToClass { class Program { static void Main(string[] args) { string str = "A"; Type type = Type.GetType(new Program().GetType().Namespace+"."+str,true,true); var temp= Activator.CreateInstance(type); A a = temp as A; a.PintA(); } } public class A { public A() { } public void PintA() { Console.WriteLine("A"); } } }