首页 > 解决方案 > 带有接口参数的接口方法,其中实现有自己的类作为参数

问题描述

假设我有以下界面:

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#genericsinheritancemethodsinterface

解决方案


为了说明我的评论:

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 的文章


推荐阅读