对象转换对同属性进行赋值
2011-06-19 21:07
399 查看
using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Reflection; namespace WebLinq { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { User u = new User(); u.Age = 18; u.Name = "rhythmk"; Man man = new Man(); SetValue(u, man); if (man != null) { Response.Write(man.Name); } else { Response.Write("NULL"); } } public static void SetValue(object oldObj, object newObj) { Type oldType = oldObj.GetType(); Type newType = newObj.GetType(); PropertyInfo[] oldObjPropertyInfos = oldType.GetProperties(); for (int i = 0; i < oldObjPropertyInfos.Length; i++) { if (oldObjPropertyInfos[i].CanRead) { string strPropertyName = oldObjPropertyInfos[i].Name; object newValue = GetPropertyValue(oldObj, strPropertyName); if (newValue != null) SetPropertyValue(newObj, strPropertyName, newValue); } } } private static void SetPropertyValue(object obj, string strPropertyName, object val) { Type t = obj.GetType(); PropertyInfo[] propertyInfos = t.GetProperties(); foreach (PropertyInfo pi in propertyInfos) { if (pi.Name == strPropertyName) { if (pi.CanWrite) pi.SetValue(obj, val, null); } } } private static object GetPropertyValue(object obj, string strPropertyName) { Type t = obj.GetType(); PropertyInfo[] propertyInfos = t.GetProperties(); foreach (PropertyInfo pi in propertyInfos) { if (pi.Name == strPropertyName) { if (pi.CanRead) return pi.GetValue(obj, null); } } return null; } } }
主要是 避免在项目开发中 比如 Linq to sql 生成的数据类 跟实际的类 之间 进行赋值
而无需去进行
a.property1=b.property1;
a.property2=b.property2;
a.property3=b.property3;
相关文章推荐
- C# 匿名类型 对象 转换成 其他 匿名类对象(具有 相同特性值 的 属性 之间的赋值)
- 代码 - 通过反射对象属性进行遍历赋值
- C# 反射给对象属性赋值遇到的问题——类型转换
- 对不同对象的相同属性进行赋值,被改变的是des
- java list按照元素对象的指定多个字段属性进行排序
- python中 class 或对象属性转化成dict 、dict转换成对象
- Javascript 创建对象及为对象属性赋值
- DOM对象和JQuery对象进行转换
- DozerBeanMapper对象之间相同属性名赋值
- web开发中如何对json对象的某一属性对其进行排序
- 晚绑定场景下对象属性赋值和取值可以不需要PropertyInfo
- 利用Gson进行String和对象的转换
- javascript对象转换,动态属性取值
- java使用Comparator根据list对象的属性进行排序
- OC中Foundation集合的使用(其中包括基本数据类型与对象进行转换)
- lua 对C++对象进行转换
- java list按照元素对象的指定多个字段属性进行排序
- spring源码探究---beanFactory为bean对象设置属性时涉及到的类型转换
- 对"对象的多个属性"进行匹配搜索& 4000 quot;对象数组"的算法
- 在JAVASCRIPT中构建一个复杂的对象,并用JSON进行转换