想简化一些代码,就研究了一下反射,资料不少,感觉挺难,搞得似是而非。写了个小东西回顾一下反射的用法。
建一个User类
class User {
private string userid = "0001";
public string Userid
{
get { return userid; }
set { userid = value; }
}
private string userName = "aaa";
public string UserName{
get { return userName; }
set { userName = value; }
} private string address = "bbb";
public string Address{
get { return address; }
set { address = value; }
}
private string email = "ccc";
public string Email{
get { return email; }
set { email = value; }
}
private string phone = "ddd";
public string Phone
{
get { return phone; }
set { phone = value; }
} }
假如有个winform有个Phone属性,其值为88888888,可以这样来对其封装:
Type type = typeof(User);
object obj = Activator.CreateInstance(type); PropertyInfo[] props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance);
User user=new User();
foreach (PropertyInfo p in props)
{
if (p.Name == "Phone")
{
p.SetValue(user, "88888888");
}
}
Console.WriteLine(user.Phone+" "+user.Email+" "+user.Address);
Console.ReadKey();