C#如何使用反射实现通过字符串创建类

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

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

}

参考C#如何使用反射实现通过字符串创建内部类??  

posted @ 2011-07-21 10:39  焦涛  阅读(10153)  评论(1编辑  收藏  举报