使用 AutoMapper,是否可以将 属性 值映射到 属性?

Using AutoMapper, is it possible to map a property value to a property?

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

考虑以下因素:

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 实例列表,我正在尝试根据 "Val" 属性 的值将 ClassB 的值转换为 ClassA 的正确 属性 "Name":

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 或任何其他工具?

is it possible using AutoMapper or any other tool?

您可以使用 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 的 属性。

我曾经找到过这段代码 on SO,并且从那以后我就一直在使用它来做这些事情。您将此扩展方法放入 class:

    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;