c# - 带有接口参数的接口方法,其中实现有自己的类作为参数
问题描述
假设我有以下界面:
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) {...}
}
解决方案
为了说明我的评论:
interface IShape
{
bool Intersect(IShape shape);
}
class Circle : IShape
{
public bool Intersect(IShape shape)
{
switch (shape)
{
case Circle circle:
// Circle / circle intersection
break;
case Rectangle rectangle:
// Circle / rectangle intersection
break;
....
default:
throw new NotImplementedException();
}
}
}
或者使用完全不同的类来处理交叉点,如Eric Lippert 的文章
推荐阅读
- python - 如果不存在,则使用 defaultdict 处理对键的动态插入
- java - 如何在标签中显示用户名登录
- javascript - Mongodb 使用可选方法连接对象
- c# - 关于 FullRowSelected 属性
- asp.net-core-2.1 - 如何将动态添加的 jQuery 标记绑定到 asp.net core mvc 中的 httpost 控制器操作?
- zebra-printers - 打印模式命令
- javascript - createStore如何从redux中的reducer函数中提取initialState?
- java - org.testng.TestNGException 在类路径中找不到类
- javascript - TintMCE - 单击按钮后更改文本字体大小
- javascript - 删除后自定义元素仍在运行