繁体   English   中英

使用接口作为字段类型,但让基类选择派生的结构

[英]Using an interface as a field type but have the base class pick the derived struct

标题可能没有什么描述性,但是我将在这里尝试尽可能清楚地说明情况。 我创建了一个将由其他人继承的类继承的类。 我的班级使用我创建的IShape接口包含一个形状结构变量,如下所示:

IShape Bounds = new Rectangle(/*arguments go here*/);

如何让最终用户控制要使用的形状,同时仍允许他访问所选形状的方法和字段(不取消装箱24/7)? 基本上,我希望用户选择自己想要的形状,但仍具有IShape表单中的形状来执行诸如碰撞之类的操作。 例如:

Bounds = new Triangle(/*arguments*/);
Bounds.Point3 = new Point(20f, 20f); //this property would be from the Triangle : IShape struct only and is not inherited from IShape

有什么方法或解决方法可以使最终用户轻松实现这一目标?

一种可能的解决方案是使用具有接口约束的通用类。 因此,声明将类似于:

public class MyClass<TShape> where TShape : IShape
{
    protected TShape Bounds;
    //Rest of class
}

另外,您可以通过通用方法提供对形状的访问权限,该方法可以集中进行铸造的位置:

public class MyClass
{
    private IShape Bounds;

    protected TShape GetBounds<TShape>() where TShape : IShape
    {
        return (TShape)Bounds; //Note this will throw an exception if the wrong shape is specified
    }
    //Rest of class
}

如果基类应负责了解其自身的形状类型,则前者更合适。 如果基类应保持对形状类型的了解,而继承类(或将类设为公共的调用类)应知道,则后者更合适。

但是,尽管这些解决方案之一可能非常适合您的情况,但必须完全做到这一点有点代码味。 如果您的班级大多数时候不得不知道并跟踪特定的具体班级,那么使用接口没有多大意义。 最好的解决方案可能是更改设计,尽管要在不了解更多内容的情况下很难给出建议。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM