【问题标题】:Using AutoMapper, is it possible to map a property value to a property?使用 AutoMapper,是否可以将属性值映射到属性?
【发布时间】:2016-01-31 22:09:10
【问题描述】:

我正在使用 AutoMapper for C#,我正在尝试将属性值转换为属性名称。

考虑以下几点:

public class ClassA
{
    public string ParamA { get; set; }
    public string ParamB { get; set; }
}

public class ClassB
{
    public string Name { get; set; }
    public string Val { get; set; }
}

我有一个 ClassB 实例列表,我正在尝试根据“Name”的值将 ClassB 中的“Val”属性值转换为 ClassA 的正确属性:

ClassB b1 = new ClassB() {Name = "ParamA", Val = "ValueA"};
ClassB b2 = new ClassB() {Name = "ParamB", Val = "ValueB"};
ClassB b3 = new ClassB() {Name = "ParamC", Val = "ValueC"};
List<ClassB> listB = new List<ClassB>() {b1, b2, b3};

所以使用 listB 我正在尝试使用 ParamA = "ValueA"ParamB = "ValueB" 创建类型为 ClassA 的对象,是否可以使用 AutoMapper 或任何其他工具?

【问题讨论】:

    标签: c# automapper


    【解决方案1】:

    是否可以使用 AutoMapper 或任何其他工具?

    您可以使用Reflection 执行以下操作:

    ClassA a = new ClassA();
    
    foreach (var b in listB)
    {
        typeof(ClassA)
            .GetProperty(b.Name) //Get property of ClassA of which name is b.Name
            .SetValue(a , b.Val); //Set the value of such property on object a
    }
    

    请注意,根据您的问题,ClassA 应该有一个名为 ParamC 的属性。

    【讨论】:

      【解决方案2】:

      我曾经发现过这段代码on SO,并且我一直使用它来处理这些事情。你把这个扩展方法放到你的类中:

          public object this[string propertyName]
          {
            get { return this.GetType().GetProperty(propertyName).GetValue(this, null); }
            set { this.GetType().GetProperty(propertyName).SetValue(this, value, null); }
          }
      

      然后就可以用[]来做

      ClassA a;
      ClassB b;
      ...
      a[b.Name] = b.Val;
      

      【讨论】:

      • 我没有提到 ClassA 是第 3 方,所以我无法为其添加索引器。不过,您可能是正确的,最好的方法是使用反射。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-30
      相关资源
      最近更新 更多