我想知道如何映射两个不同对象的字段并为其分配值。
示例:
public class employee
{
public int ID { get; set; }
public string Name { get; set; }
}
public class manager
{
public int MgrId { get; set; }
public string MgrName { get; set; }
}
现在我有了一个列表对象。我想将值分配给“经理”类。任何自动的方式来做到这一点。我可以明确地做到这一点并为其赋值。但是我的对象非常大,这就是问题所在。我也不想使用任何第三方工具。
注意:不能有manager前缀。它可以是任何东西。 (例如:mgrId 可以类似于 mgrCode)
最佳答案
您可以为它使用反射,甚至忽略属性大小写(注意 employee.ID
与 manager.MgrId
):
class Program
{
static void Main(string[] args)
{
var employee = new Employee() { ID = 1, Name = "John" };
var manager = new Manager();
foreach (PropertyInfo propertyInfo in typeof(Employee).GetProperties())
{
typeof(Manager)
.GetProperty("Mgr" + propertyInfo.Name,
BindingFlags.IgnoreCase |
BindingFlags.Instance |
BindingFlags.Public)
.SetValue(manager,
propertyInfo.GetValue(employee));
}
}
}
public class Employee
{
public int ID { get; set; }
public string Name { get; set; }
}
public class Manager
{
public int MgrId { get; set; }
public string MgrName { get; set; }
}
如果不知道Mgr
前缀,只能通过后缀匹配:
foreach (PropertyInfo propertyInfo in typeof(Employee).GetProperties())
{
typeof(Manager).GetMembers()
.OfType<PropertyInfo>()
.FirstOrDefault(p => p.Name.EndsWith(propertyInfo.Name,
StringComparison.CurrentCultureIgnoreCase))
.SetValue(manager,
propertyInfo.GetValue(employee));
}
并且一个非常狭窄且不切实际的假设:基于属性顺序的映射(如果您希望这两种类型具有以相同顺序和编号定义的属性,唯一的区别是属性名称).我不建议任何人在现实生活中使用它,但它仍然在这里(只是为了让它更脆弱 :)):
typeof(Employee)
.GetProperties()
.Select((p, index) =>
new { Index = index, PropertyInfo = p })
.ToList()
.ForEach(p =>
{
typeof(Manager)
.GetProperties()
.Skip(p.Index)
.FirstOrDefault()
.SetValue(manager,
p.PropertyInfo.GetValue(employee));
});
关于c# - 如何映射两个不同对象的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17675408/