【问题标题】:Manual Mapping with Inhertance带继承的手动映射
【发布时间】:2022-01-20 16:01:08
【问题描述】:

假设我有两个类 A 和 ADto。 A 继承自 ABase,ADto 继承自 ADtoBase。

我有两种扩展方法可以手动将 ABase 映射到 ADtoBase,反之亦然。 当我想编写一个扩展方法来将 A 映射到 ADto 时,有没有办法重用基本对话以避免重复?即,我不想为基类中存在的字段正确映射并为此重用基本映射器。

例子:

Class ABase:
+ string Id;

Class ADtoBase:
+ string Id;

Class A: ABase:
+ string Name;

Class ADto:ADtoBase
+ string Name

public static ADto ToADto(this ADtoBase)
{
// I somehow want to use the base mapper (extension) so that I don't have to map Id again and only map Name.
}

【问题讨论】:

  • 如果你用实际的类定义而不是准 UML(或你想在那里做的任何事情)来呈现它会更好。

标签: c# inheritance mapping extension-methods dto


【解决方案1】:

你可以使用这样的方法:

void MapBaseClassProperties(ABase source, ADtoBase target) // Awful method name!
{
    target.Id = source.Id;
    target.Name = source.Name;
}

继承类型的映射方法可以创建目标类型的实例并映射基类中的任何属性。

然后它可以将原始和映射“目标”都传递给为基类属性进行映射的方法。换句话说,这是:

public Adto MapToDto(A source)
{
    var target = new Adto();
    // map the properties that aren't in the base class
    target.SomeOtherProperty = source.SomeOtherProperty;

    // map the properties that are in the base class.
    MapBaseClassProperties(source, target);
    return target;
}

【讨论】:

    猜你喜欢
    • 2017-04-11
    • 1970-01-01
    • 1970-01-01
    • 2017-12-07
    • 2011-11-22
    • 2010-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多