【问题标题】:Combining/converting 2 similar object types from 2 different APIs组合/转换来自 2 个不同 API 的 2 个相似对象类型
【发布时间】:2013-11-14 19:19:52
【问题描述】:

我是 C# 和 OOP 的初学者。我正在使用两个第 3 方 API,它们包含相似的对象类型,这些对象类型的属性包含相同的值,但两个 API 都有我需要使用的独特(且相同)的功能。例如:

API1 - 点类

公共财产

X : 双倍

Y : 双倍

公共方法

距离()

ToArray()

API2 - 点类

公共财产

X : 双倍

Y : 双倍

公共方法

项目()

ToArray()

目前我已经制作了从 API1 Point 类转换为 API2 Point 类的辅助方法,反之亦然,但必须有更好的解决方案。在这种情况下,编程专家会怎么做?谢谢!

【问题讨论】:

  • 你用 API1 和 API2 的 Point 类做什么?您是否正在处理来自一个 API 的点对象作为另一个 API 的输入?
  • 根据用户的操作,我可能需要使用其中一种独特的功能。例如 API1 处理可视化和 UI,但有一些独特的功能(将样条线转换为点)然后我使用 API2,它是纯数学函数来提供点。所以我需要将 API1 点实体转换为 API2 点实体才能使函数工作。完成后 API2 返回一堆 API2 点,我需要将它们转换回 API1 点以显示在屏幕上。

标签: c# oop design-patterns


【解决方案1】:

包装类和显式转换操作可以解决您的问题。

public class IntergratedPoint{
    // private constructor to prevent misuse
    // If want, you can do a normal constructor which create both pointApi1 and 2
    private IntergratedPoint(){ }

    // this can be set to reference either pointApi1 or 2
    public double X{get;set;} 
    public double Y{get;set;}

    private Api1.Point pointApi1;
    private Api2.Point pointApi2;

    public static explicit operator IntegratedPoint(Api1.Point pointApi1){
        IntegratedPoint newPoint = new IntegratedPoint();
        newPoint.pointApi1 = pointApi1;
        newPoint.pointApi2 = new Api1.Point();
        // set X and Y for pointApi2
    }

    // the explicit operator for Api2.Point

    public double Distance(){
        return pointApi1.Distance();
    }
    public double Project(){
        return pointApi2.Project();
    }
    public double[] ToArray(){
        // don't know what to do, but it you can do either pointApi1.ToArray() or so
    }    
}

【讨论】:

  • 芬迪,我喜欢这种方法。以确保我完全理解。我创建了自己的点类,其中包含每个 API 的一个点、显式运算符和我需要的两个 API 的方法。然后我可以通过将任何 API 点转换为我自己的 IntergratedPoint 来使用我的类?
  • 正确。这样,您可以同时使用这两个类,同时仍然控制自己的流程。铸造可以用构造函数注入代替,不过这取决于你的口味。
【解决方案2】:

您可以使用Automapper。它使您能够定义映射

Mapper.CreateMap<Order, OrderDto>();

然后到处使用它

OrderDto dto = Mapper.Map<OrderDto>(order);

【讨论】:

  • 我没有看到实际证据表明这对 OP 有何帮助。
【解决方案3】:

我最终为 API1 Point 类添加了各种扩展方法。使用类型转换辅助方法,我可以让 API1 点类使用 API2 点类方法。有了这个,我只在我的代码中使用 API1 点对象。

【讨论】:

    猜你喜欢
    • 2018-03-04
    • 2019-03-13
    • 2018-10-07
    • 2023-03-10
    • 2019-09-28
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多