最近在学反射,遇到干货就总结记录下;
这里我自己实例化一个类对象进行反射,实际上也可以自己利用反射实例化对象
参考https://blog.csdn.net/weixin_42609389/article/details/83992866
private void Form1_Load(object sender, EventArgs e)
{
try
{
Person nc = new Person();
//写
Type Ts = nc.GetType();
object v = Convert.ChangeType("libai", Ts.GetProperty("Name").PropertyType);
Ts.GetProperty("Name").SetValue(nc, v, null);
//读
object test = Ts.GetProperty("Name").GetValue(nc);
//调用成员函数输出
Ts.GetMethod("ShowIdentify").Invoke(nc, new object[] { test });
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
class Person
{
public int num;
public string name;
public bool man;
public double weight;
public string info;
public string MyInfo
{
get { return info; }
set { info = value; }
}
public int ID
{
get { return num; }
set { num = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public bool Man
{
get { return man; }
set { man = value; }
}
public double Weight
{
get { return weight; }
set { weight = value; }
}
public void ShowIdentify(object var)
{
MessageBox.Show(var.ToString());
}