我有这些课程
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
public virtual Address Address { get; set; }
}
public class Address
{
public string Line1 { get; set; }
public string Line2 { get; set; }
}
public class Flat
{
public int ID { get; set; }
public string Name { get; set; }
public virtual Address Address { get; set; }
}
这是我用来设置Flat class
上的值的代码var employee = new Employee() { ID = 1, Name = "Test", Address = new Address() {Line1 = "1", Line2 = "2" } };
Flat flat = new Flat();
Map(employee, flat);
static void Map<TI, VI>(TI source, VI result)
{
foreach (PropertyInfo item source.GetType().GetRuntimeProperties())
{
if (item.GetValue(source) != null)
{
if (result.GetType().GetRuntimeProperty(item.Name) != null)
{
Type type = result.GetType().GetRuntimeProperty(item.Name).PropertyType;
var innerObj = FormatterServices.GetUninitializedObject(type);
result.GetType().GetRuntimeProperty(item.Name).SetValue(result, innerObj);
Map(item.GetValue(source), innerObj);
}
else
{
Map(item.GetValue(source), result);
}
}
}
}
}
如果你能告诉我这是否是映射嵌套属性的正确方法,我真的很感激。如果不是这种情况,请提供替代方案。