反射

class Program
{
string name;
int age;
public string Name
{
get { return name; }
set { this.name = value; }
}
static void Main(string[] args)
{
//无参构造函数来实例化类
object obj = Assembly.Load("ConsoleApp").CreateInstance("ConsoleApp.Program");
Type type = obj.GetType();
MethodInfo methodinfo1 = type.GetMethod("GetName", new Type[0]);
MethodInfo methodinfo2 = type.GetMethod("GetName", new Type[] { typeof(string), typeof(string) });
MethodInfo methodinfo3 = type.GetMethod("GetAge", BindingFlags.Instance | BindingFlags.NonPublic);
PropertyInfo propertyInfo1 = type.GetProperty("Name");
FieldInfo fieldInfo1 = type.GetField("name", BindingFlags.Instance | BindingFlags.NonPublic);
fieldInfo1.SetValue(obj, "wwb");
object re1 = methodinfo1.Invoke(obj, null);
object re2 = methodinfo2.Invoke(obj, new object[] { "fdf", "fd" });
object re3 = methodinfo3.Invoke(obj, null);
propertyInfo1.SetValue(obj, "王文斌", null);
object re4 = propertyInfo1.GetValue(obj, null);
object re5 = fieldInfo1.GetValue(obj);

Console.WriteLine("无参数的公共方法:" + re1);
Console.WriteLine("有参数的公共方法:" + re2);
Console.WriteLine("无参数的私有方法:" + re3);
Console.WriteLine("属性:" + re4);
Console.WriteLine("字段:" + re5);

//有参构造函数来实例化类
Assembly assembly = Assembly.Load("ConsoleApp");
Type type2 = assembly.GetType("ConsoleApp.Program");
ConstructorInfo constructorInfo = type2.GetConstructor(new Type[] { typeof(string), typeof(int) });
object instance = constructorInfo.Invoke(new object[] { "wwb", 27 });
}
public Program()
{
}
public Program(string name, int age)
{
this.name = name;
this.age = age;

Console.WriteLine("i have two parameter constructor:" + name + ":" + age);
}
public string GetName(string name, string abc)
{
return name;
}
public string GetName()
{
return name;
}
int GetAge()
{
return age;
}
}
posted @ 2012-03-01 10:13  pantherbean  阅读(185)  评论(0编辑  收藏  举报