Si potrebbe utilizzare la riflessione per esso, anche ignorando l'involucro di proprietà (si noti il 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; }
}
Se non si conosce il prefisso Mgr
, si poteva solo incontro da suffissi:
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));
}
e un assunto molto stretta e poco pratico: mappatura B sull'ordine delle proprietà (se si prevede che i 2 tipi abbiano proprietà definite nella stessa sequenza e numero, l'unica differenza sono i nomi delle proprietà). Io non lo consiglio a chiunque di utilizzarlo nella vita reale, ma ancora, qui è (solo per renderlo più fragile :)):
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));
});
fonte
2013-07-16 11:45:31
* "Non voglio utilizzare strumenti di terze parti troppo. "* Perchè no? –
Usa la riflessione http://msdn.microsoft.com/en-us/library/f7ykdhsy.aspx –
Solo un suggerimento: http://automapper.org/, è un ottimo strumento per convertire oggetti come questo. –