我正在使用AutoMapper将对象映射到彼此。我的一个对象有几个属性,它们是其他对象的集合。我试图想出一种通用的方法来映射各种对象,直到运行时才知道它们是什么。这是我到目前为止的示例代码:
public class Person
{
public List<Sibling> Siblings;
public List<Pet> Pets;
public List<Vehicle> Vehicles;
}
static void DoStuff(List<PersonInfo> people)
{
Dictionary<Type, Type> dictionary = new Dictionary<Type, Type>();
{
dictionary.Add(typeof(SiblingInfo), typeof(Sibling));
dictionary.Add(typeof(PetInfo), typeof(Pet));
dictionary.Add(typeof(VehicleInfo), typeof(Vehicle));
//MANY MORE ENTRIES
//.................
//END
}
using (MyEntities db = new MyEntities())
{
foreach (PersonInfo personInfo in people)
{
Person newPerson = Mapper.Map<Person>(personInfo);
foreach (PropertyInfo propertyInfo in personInfo.GetType().GetProperties())
{
if (propertyInfo.PropertyType.IsArray)
{
Array array = (Array)propertyInfo.GetValue(personInfo);
for (int i = 0; i < array.Length; i++)
{
dynamic objectInfo = array.GetValue(i);
Type sourceType = objectInfo.GetType();
Type destinationType;
if (dictionary.TryGetValue(sourceType, out destinationType)) ;
dynamic newObject = Mapper.Map(objectInfo, sourceType, destinationType);
//HOW TO ADD THE NEW OBJECT TO ITS RESPECTIVE COLLECTION???
//newPerson.Siblings.Add(newObject);
//newPerson.Pets.Add(newObject);
//newPerson.Vehicles.Add(newObject);
//newPerson.HOW_TO_ADD_THIS.Add(newObject);
}
}
}
}
//DO MORE STUFF
//........
//END
}
}
无论类型如何,这都可以很好地进行映射。我正在努力解决的问题是在这段代码的底部,我需要将新对象添加到父对象的适当集合属性中。
如何修改此代码以将新对象添加到相应的集合中?
答案 0 :(得分:0)
如果我理解正确,您可以通过反射获取集合属性,然后在那里添加新值 - 如下所示:
class Program {
static void Main(string[] args) {
var person = new Person();
var prop = person.GetType().GetProperty("Siblings");
var currentValue = (IList) prop.GetValue(person);
currentValue.Add("new object");
Console.WriteLine(person.Siblings);
}
}
public class Person {
public Person() {
Siblings = new ObservableCollection<string>();
}
public ObservableCollection<string> Siblings { get; private set; }
}
如果collection属性可以为null - 请确保在添加值之前对其进行初始化。