-1
嗨有我有这些源和目标类,并在映射ICollection SomeClasses {get; set}属性卡住。我简化了它们,但实际的类很复杂。如何使用反射映射集合属性
public class Source
{
public string Name{get; set;}
public ICollection<SomeClass> SomeClasses {get;set}
}
public class Result
{
public string Name{get; set;}
public ICollection<SomeClass> SomeClasses {get;set}
}
public class SomeClass
{
public string Name {get; set;}
public string SomeThing {get;set}
}
这是我玩的代码,没有运气。
public object Map(object source, object result)
{
foreach (PropertyInfo item in source.GetType().GetRuntimeProperties())
{
if (item.PropertyType.IsGenericType && item.PropertyType.GetInterface(typeof(IEnumerable<>).FullName) != null)
{
Type type = item.PropertyType.GetGenericArguments()[0];
var innerObj = FormatterServices.GetUninitializedObject(type);
var listType = typeof(List<>);
var constructedListType = listType.MakeGenericType(innerObj.GetType());
var newList = (IList)Activator.CreateInstance(constructedListType);
IEnumerable listValue = (IEnumerable)item.GetValue(source);
IEnumerable listValue = (IEnumerable)item.GetValue(source);
//newList.Add(innerObj);
//item.SetValue(source, newList);
foreach (var val in listValue)
{
newList.Add(val);
}
//list.Add(obj4);
//option a
//result.GetType().GetRuntimeProperty(item.Name).SetValue(result, newList);
//option b
result.GetType().GetRuntimeProperty(item.Name).SetValue(result, item.GetValue(source));
}
}
}
有一个名为AutoMapper的库可以完成这个工作。你看过吗? – PoweredByOrange
你到底在挣扎什么?你遇到什么错误?针对您遇到的特定问题添加更多精确度将会产生更多更好的答案 – Louis
@PoweredByOrange感谢您的建议。 AutoMapper是伟大的,但这需要我对属性名称进行如此多的更改,这对我来说是不可行的,因为我将不得不经历大约5000条代码行。在这里写下自己的25行是很棒的。 – Raider