您的位置:首页 > 编程语言 > C#

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

2011-01-20 22:46 183 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: