下面我们写一个例子来看看反射的作用
例1:类似与Winform里面的PropertyGrid的控件功能
我们实现一个类似与Winform里面的PropertyGrid的控件功能,不懂的同学可以去百度下PropertyGrid是什么。
class Program
{
static void Main(string[] args)
{
Person p = new Person()
{
Age = 12,
Name="你好啊"
};
MyPropertyGird(p);
Console.ReadKey();
}
private static void MyPropertyGird(object obj)
{
Type type = typeof(Person);
PropertyInfo[] propertyInfo = type.GetProperties();
foreach (var item in propertyInfo)
{
if (item.CanRead)
{
Console.WriteLine(item.Name + ":" + item.GetValue(obj));
}
}
}
}
public class Person
{
public int Age { get; set; }
public string Name { get; set; }
}
就是能够正常显示一个对象的属性的名字以及对应的值。
例2.对象的深拷贝
我们以前在进行拷贝对象的时候。用的是如下的这种方式来拷贝对象
Person p1 = new Person();
p1.Name = "张三";
p1.Age = 12;
Person p2 = new Person();
p1.Name = "张三";
p1.Age = 12;
Person p3 = new Person();
p1.Name = "张三";
p1.Age = 12;
Person p4 = new Person();
p1.Name = "张三";
p1.Age = 12;
这样如果要复制很多份,靠这样去复制太慢了,而且相当的费时间!所以我们可以用反射来减轻工作量
static void Main(string[] args)
{
Person p1 = new Person();
p1.Name = "张三";
p1.Age = 12;
Person p2 = (Person)MyClone(p1);
MyPropertyGird(p2);
Console.WriteLine("---------------------------------------------");
Person p3 = (Person)MyClone(p1);
MyPropertyGird(p3);
Console.ReadKey();
//Person p2 = new Person();
//p1.Name = "张三";
//p1.Age = 12;
//Person p3 = new Person();
//p1.Name = "张三";
//p1.Age = 12;
//Person p4 = new Person();
//p1.Name = "张三";
//p1.Age = 12;
}
public static object MyClone(object obj)
{
Type type = obj.GetType();
object cloneObj = Activator.CreateInstance(type);//创建一个复制的对象
PropertyInfo[] propertyInfos = type.GetProperties();//获取要复制的所有的公共属性值
foreach (var item in propertyInfos)
{
//cloneObj.GetType()为转换为指定的类类型
//cloneObj.GetType().GetProperty(item.Name)要复制的属性
//cloneObj.GetType().GetProperty(item.Name).SetValue(cloneObj, item.GetValue(obj));给要复制的属性复制值
cloneObj.GetType().GetProperty(item.Name).SetValue(cloneObj, item.GetValue(obj));
}
return cloneObj;
这样我们只需要写一句代码就可以实现对象的深拷贝了!!!
---本博客是学习以后记录知识,如有侵权,请联系删除!!!