不同类型的抽象

时间:2017-01-31 12:57:03

标签: c# oop interface abstraction

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

这就是我现在所拥有的:

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...
    }

}

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

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()的情况下实现这一点,并且只能在客户端中直接使用抽象/多态?

由于

1 个答案:

答案 0 :(得分:2)

使用Generics

line one
line two

然后,将您的服务界面更改为:

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);
}
相关问题