【发布时间】:2018-08-20 14:40:51
【问题描述】:
我正在重构一个旧库,其中包含如下类:
public class Template //Old one
{
public double Value { get; set; }
}
现在最好提供更多的灵活性来允许用户定义Value 类型。于是我把Template改成了泛型类:
public class Template<T>
{
public T Value { get; set; }
}
此更改打破了其他人对旧 Template 类的用法,因此我尝试添加向后兼容性(允许其他人以旧方式使用我的库):
public class Template: Template<double> { }
但它也需要对库进行大量更改。尤其是在使用旧的Template的地方,比如:
public class AnotherClassInLibrary<T>
{
public Template<T> API() {...}
}
public class AnotherClassInLibrary : AnotherClassInLibrary<double>
{
// This class is also defined for the old way of using the library
public Template API()
{
return base.API();
// Error here: Template<double> cannot be implicitly convert to Template.
}
}
所以问题来了:新的Template 是从Template<double> 继承的,所以在这里转换不是一个好的/有效的做法。是否有解决方法来保持AnotherClassInLibrary 向后兼容而不重写API() 代码两次?
附:我真的希望 C# 在 C++ 中有类似 typedef 的东西。但是the answer is NO。
【问题讨论】:
-
你的非泛型
Template类在哪里? -
如果另一个类型实现了
Template<double>,你还希望该强制转换有效吗? -
“虽然
Template完全是Template<double>” - 不,不是,它是继承链更深的一类。 -
您正在尝试从父母投射到孩子。如果你有
Template<int> a怎么办?你还想投吗? -
仅仅因为你没有提供新功能,这仍然不会使
Template成为@987654341 类型的某种同义词 或别名 @。它们是不同的类型。