【问题标题】:Updating property of child properties using recursion使用递归更新子属性的属性
【发布时间】:2014-09-12 15:30:13
【问题描述】:

我正在构建一个映射引擎。

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

如何在“员工”的 2 个级别中更新“TheAddressType”

谢谢!

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; }
}

【问题讨论】:

  • 你可以使用反射。但为什么它首先是一个字符串呢?
  • 您真的应该避免尝试将字符串作为代码执行。它非常不安全、容易出错、效率低下,而且对所有相关人员都没有乐趣。
  • “我正在构建一个映射引擎。” : 你听说过 AutoMapper 吗? (automapper.org)
  • Automapper 在我们这里的情况下不起作用(或者至少我对它的了解不适用)。我无法控制引入路径的方式,这就是数据(存储在表中)的方式。

标签: c# recursion mapping


【解决方案1】:

好吧,如果真的无法改变任何现有的东西.....

我相信这就是您要找的:

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; }
}

【讨论】:

  • 谢谢!是的,这是一个奇怪的要求。
猜你喜欢
  • 2019-06-27
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 2016-06-02
  • 2014-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多