
正文
c# 反射小Demo
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
今天看了一下C#的反射,之前一直感觉反射是一种很高大上的东东,现在才发现不过是纸老虎而以.
所谓的反射就是,只是知道一个它是一个对象不知道其中有什么字段方法属性等,而反射就是用来获取一个未知对象的字段方法事件等.
下面是从网上看到的一个小例子,
class Person
{
private string _Name;
private int _Age;
private string _Sex; public string Name
{
get { return this._Name; }
set { this._Name = value; }
} public int Age
{
get { return this._Age; }
set { this._Age = value; }
} public string Sex
{
get { return this._Sex; }
set { this._Sex = value; }
}
}
上面写的是需要操作的类,下面是进行实地操作
class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Name = "snoopy";
person.Age = ;
person.Sex = "male"; //
PropertyInfo[] infos = person.GetType().GetProperties();
//获取属性 (只限字段)
foreach (PropertyInfo info in infos)
{ Console.WriteLine("属性的类型是" + info.PropertyType + "属性的名称是" + info.Name + ":" + "属性的数值是" + info.GetValue(person, null));
} Console.WriteLine("设置Person.Name = Hellokitty");
//设置属性
foreach (PropertyInfo info in infos)
{
if (info.Name == "Name")
{
info.SetValue(person, "Hellokitty", null);
}
}
}
}






