【发布时间】:2019-07-18 02:16:12
【问题描述】:
假设我有如下界面:
interface IShape
{
bool Intersect(IShape shape);
}
那我想要下面的具体实现:
class Circle : IShape
{
bool Intersect(Circle shape) {...}
}
class Rectangle : IShape
{
bool Intersect(Rectangle shape) {...}
}
在 C# 中是否有任何聪明的方法可以在不使用泛型的情况下做到这一点? 即任何不是这样的方式:
interface IShape<T> where T : IShape<T>
{
bool Intersect(T shape);
}
class Circle : IShape<Circle>
{
bool Intersect(Circle shape) {...}
}
【问题讨论】:
-
为什么不想使用泛型?
-
在编译时,没有办法在 C# 中表达“返回或采用与声明类型相同类型的参数的方法”。您最好的选择是采用
IShapein 参数并在运行时检查实际类型,这也允许您与多种形状类型相交。 -
@Sweeper 因为如果我使用泛型,我认为没有办法声明泛型
IShape。我必须声明一个IShape<Rectangle>或IShape<Circle>,但我不能有一个“任何”IShape。 -
@DadeKuma 推荐阅读:ericlippert.com/2015/04/27/wizards-and-warriors-part-one
-
@DadeKuma 假设您可以在没有泛型的情况下这样做,这里我有一个名为
IShape的变量x。我可以将什么类型传递给x.Intersect?IShape?这意味着我可以将Circle传递给它,如果x在运行时是Rectangle,我不能。
标签: c# generics inheritance methods interface