说明:由于工作原因,本人使用反射的机会不是很多,所以没有必要为了炫耀技术而使用这种技术,不过今天有人问到这方面的问题,所以做了一个简单例子,供初学者参考,代码如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace AssemblyDemo
{
public class Person
{
private int age;
private string name;
public Person()
{
age = 20;
name = "未知";
}
{
public class Person
{
private int age;
private string name;
public Person()
{
age = 20;
name = "未知";
}
public Person(int age, string name)
{
this.age = age;
this.name = name;
}
{
this.age = age;
this.name = name;
}
public override string ToString()
{
return String.Format("姓名={0},年龄={1}", name, age);
}
}
}
{
return String.Format("姓名={0},年龄={1}", name, age);
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;//注意要添加这个命名控件的引用
namespace AssemblyDemo
{
public class Program
{
public static void Main(string[] args)
{
Assembly asm=Assembly.Load("AssemblyDemo");
Type pt = asm.GetType("AssemblyDemo.Person");//注意这里用全路径AssemblyDemo.Person而不是Person
Person p =(Person) Activator.CreateInstance(pt);//创建不带参数的实例
Console.WriteLine(p.ToString());
Person p2 = (Person)Activator.CreateInstance(pt,30,"zhoufoxcn");//创建带参数的实例
Console.WriteLine(p2.ToString());
Console.ReadLine();
}
}
}
{
public class Program
{
public static void Main(string[] args)
{
Assembly asm=Assembly.Load("AssemblyDemo");
Type pt = asm.GetType("AssemblyDemo.Person");//注意这里用全路径AssemblyDemo.Person而不是Person
Person p =(Person) Activator.CreateInstance(pt);//创建不带参数的实例
Console.WriteLine(p.ToString());
Person p2 = (Person)Activator.CreateInstance(pt,30,"zhoufoxcn");//创建带参数的实例
Console.WriteLine(p2.ToString());
Console.ReadLine();
}
}
}
程序结果如下
本文转自周金桥51CTO博客,原文链接:http://blog.51cto.com/zhoufoxcn/166989
,如需转载请自行联系原作者