新建一工程文件,选择控制台输出,起名为Exam1 ,在工程文件里新建类Student,代码如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace Exam1
{
class Student
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string sex;
public string Sex
{
get { return sex; }
set { sex = value; }
}
}
}
在Program类中编写如下代码:
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Reflection;
using System.Text;
namespace Exam1
{
class Program
{
static void Main(string[] args)
{
Student o = Activator.CreateInstance<Student>();//创建一个Student对象
Type t = typeof(Student);
NameValueCollection nvData = new NameValueCollection();
nvData.Add("Name", "lucas");
nvData.Add("Sex", "男");
foreach (string key in nvData.Keys)
{
PropertyInfo pinfo = t.GetProperty(key);
pinfo.SetValue(o, nvData[key], null);//给属性赋值
}
Console.WriteLine(o.Name);
Console.WriteLine(o.Sex);
Console.ReadLine();
}
}
}
输出结果:就是对象的两个属性值。
此类是利用C#的反射,创建一个实例,并用反射找到对象的属性,给属性赋值。
反射的使用一般是需要动态创建一个对象。大家可以把大家Copy到电脑里试试。