使用反射从同一类型的另一个实例复制所有对象值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用反射从同一类型的另一个实例复制所有对象值相关的知识,希望对你有一定的参考价值。
Say that you have a collection of objects empty but for IDs.You want to do a foreach loop through those objects and lookup detail one at a time.
Unfortunately, in the foreach, you can't replace the references, you can only copy the new detail into the object.
This technique will populate your current reference from an object instance returned by a lookup.
//Lookup result of a higher level object which has a dogs list. result.Dogs.ForEach(d => PopulateDogObject(d)); //Helper public void PopulateDogObject(IDog toDog) { IDog lookupResult = GetDogFromWebService(toDog.DogID); lookupResult.PopulateIDog(toDog); } //This is on the dog class. public void PopulateIDog(IDog toDog) { foreach (PropertyInfo pi in fromFields) { pi.SetValue(toDog, pi.GetValue(this, null), null); } }
以上是关于使用反射从同一类型的另一个实例复制所有对象值的主要内容,如果未能解决你的问题,请参考以下文章
Microsoft Access - 将对象属性复制到同一类型的另一个对象