即使忽略属性大小写,您也可以使用反射(注意employee.ID
vs. 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));
});