2014-09-12 60 views
1

我正在构建一个映射引擎。使用递归更新子属性的属性

“路径”将以字符串形式出现,此处显示为mappingAddress。 AddressAddressValue中的值是需要填充员工中已经实例化的对象2级别的值。

如何更新“TheAddressType”在2层深的“雇员”

致谢!

class Program 
{ 
    static void Main(string[] args) 
    { 
     string mappingAddress = "EmployeeAddress.ChildAddressType.TheAddressType"; 

     string theAddressTypeValue = "A Home"; 

     Employee employee = new Employee(); 

     //Magic code here 
    } 
} 

public class Employee 
{ 
    public Employee() 
    { 
     EmployeeAddress = new Address(); 
    } 

    public Address EmployeeAddress { get; set; } 
} 

public class Address 
{ 
    public Address() 
    { 
     ChildAddressType = new AddressType(); 
    } 

    public AddressType ChildAddressType { get; set; } 
} 

public class AddressType 
{ 
    public string TheAdddressType { get; set; } 
} 
+0

你可以使用反射。但为什么它首先是一个字符串呢? – 2014-09-12 15:34:44

+3

你应该真的,真的避免尝试执行字符串作为代码。这是非常不安全的,容易出错的,效率低下的,并且对于每个参与者来说都是没有乐趣的。 – Servy 2014-09-12 15:34:46

+0

“我正在构建一个映射引擎。” :你听说过AutoMapper吗? (http://automapper.org/) – Aybe 2014-09-12 15:40:38

回答

2

哦,如果有真的不能改变任何现有的东西.....

我相信这是你在找什么:

How to set Vaues to the Nested Property using C# Reflection.?

你的程序应该是这样的:

class Program 
{ 
    static void Main(string[] args) 
    { 
     string mappingAddress = "EmployeeAddress.ChildAddressType.TheAddressType"; 

     string theAddressTypeValue = "A Home"; 

     Employee employee = new Employee(); 

     //Magic code - Thanks Jon Skeet 
     SetProperty(mappingAddress, employee, theAddressTypeValue); 
    } 

    public static void SetProperty(string compoundProperty, object target, object value) 
    { 
     string[] bits = compoundProperty.Split('.'); 
     for (int i = 0; i < bits.Length - 1; i++) 
     { 
      PropertyInfo propertyToGet = target.GetType().GetProperty(bits[i]); 
      target = propertyToGet.GetValue(target, null); 
     } 
     PropertyInfo propertyToSet = target.GetType().GetProperty(bits.Last()); 
     propertyToSet.SetValue(target, value, null); 
    } 
} 

public class Employee 
{ 
    public Employee() 
    { 
     EmployeeAddress = new Address(); 
    } 

    public Address EmployeeAddress { get; set; } 
} 

public class Address 
{ 
    public Address() 
    { 
     ChildAddressType = new AddressType(); 
    } 

    public AddressType ChildAddressType { get; set; } 
} 

public class AddressType 
{ 
    public string TheAddressType { get; set; } 
} 
+0

谢谢!是的,它是一个奇怪的要求。 – 2014-10-16 14:59:07