在做项目中碰到一个问题,就是如何在知道一个类的名字,如何创建这个类呢。做的一个小测试,直接贴代码了。



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

}