【问题标题】:Abstractions for different types不同类型的抽象
【发布时间】:2017-06-16 22:13:58
【问题描述】:

我正在尝试为以下情况创建最佳抽象。也许有人可以帮忙。

这就是我现在所拥有的:

public class Point{

    public double? Value {get;set;}

    public Information DataInformation {get;set;}

}

public class RawPoint{

    //just something to process, not interesting for our example

}

public interface Service{

    List<Point> ProcessPoints(List<RawPoint> rawData);  

}

public ConcreteService : Service{

    public List<Point> ProcessPoints(List<RawPoint> rawData){
        //process the points...
    }

}

现在我有一个请求,我必须引入一种新类型的点,例如:

public class NewPointData{

    public double? Point_Max {get;set;}

    public double? Point_Min {get;set;}

}

public NewPoint {

    public NewPointData Value { get; set;}

    public Information DataInformation {get;set;}

}

我希望使用相同的 ProcessPoints() 方法拥有与之前看到的相同的 ConcreteService,而不是返回 List,我希望它返回一个可以由 Point 和 NewPoint 扩展的抽象(它们之间的唯一区别是Value 属性的数据类型)。有没有一种方法可以在不使用 typeof() 并且仅通过在客户端中直接使用抽象/多态性的情况下实现这一点?

谢谢

【问题讨论】:

  • 当您决定是否创建类层次结构或是否引入某些接口时,实际数据、行为和使用类的方式很重要。如果您只提供类名,它实际上不会提供任何信息

标签: c# oop interface abstraction


【解决方案1】:

使用Generics:

public class Point<TValue>
{
    public TValue Value { get; set; }
    public Information DataInformation { get; set; }
}

然后,将您的服务接口更改为:

public interface Service
{
    List<Point<TValue>> ProcessPoints<TValue>(List<RawPoint> rawData);
}

调用方法时需要提供泛型类型参数:

var points = _service.ProcessPoints<double?>(data);
// points is of type List<Point<double?>>

var newPoints = _service.ProcessPoints<NewPointData>(data);
// points is of type List<Point<NewPointData>>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    相关资源
    最近更新 更多