C#反射中最最最基本的东西

just look below

static void Main(string[] args)
{
//Model.Person p1 = new Model.Person();
//Model.Person p2 = new Model.Person();

//p1.Name = "Bill Gates";
//p2.Name = "Paul Jobs";

//p1.Work();
//p2.Work();

//Console.WriteLine(p1.WhatIsYourName());
//Console.WriteLine(p2.WhatIsYourName());



System.Reflection.Assembly asm
= System.Reflection.Assembly.LoadFrom(@"c:\users\polaris\documents\visual studio 2010\Projects\ConsoleApplicationReflection\Model\bin\Debug\Model.dll");
object obj1 = asm.CreateInstance("Model.Person");
object obj2 = asm.CreateInstance("Model.Person");

Type type
= obj1.GetType();

System.Reflection.PropertyInfo pi;
pi
= type.GetProperty("Name");

pi.SetValue(obj1,
"Bill Gates", null);
pi.SetValue(obj2,
"Paul Jobs", null);


System.Reflection.MethodInfo mi;
mi
= type.GetMethod("Work");
mi.Invoke(obj1,
null);
mi.Invoke(obj2,
null );

mi
= type.GetMethod("WhatIsYourName");
string val1 = mi.Invoke(obj1, null).ToString();
string val2 = mi.Invoke(obj2, null).ToString();
Console.WriteLine(val1);
Console.WriteLine(val2);
}

 

 

Model.Person类如下:

public class Person
{
public string Code { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthday { get; set; }

public void Work()
{
Console.WriteLine(
"working......");
}

public string WhatIsYourName()
{
return string.Format( "I'm {0}",this.Name);
}
}

 

 

posted @ 2011-01-20 22:46  cnbwang  阅读(206)  评论(0编辑  收藏  举报