c# - C#中如何防止非法ICloneable<T>继承?

标签 c# oop generics inheritance inheritance-prevention

我有一个界面:

public interface ICloneable<out T>
    where T : ICloneable<T>
{
    T Clone();
}

应该接收一个实现此接口(interface)的类型(如下所示)。
我可以创建一个实现它的类:

public class Class : ICloneable<Class>
{
    public Class Clone() { return (Class)MemberwiseClone(); }
}

太棒了!

但是任何人都可以创建一个“错误”实现 ICloneable 的类。
是否存在如下所示的阻止继承的方法?(2个示例)

public class Other : ICloneable<Class>
{
    public Class Clone() { return new Class(); }
}

public class Other : Class, ICloneable<Class>
{
    public Class Clone() { return (Other)MemberwiseClone(); }
}

并允许继承,如下所示? (任意 2 个示例)

public class Other : ICloneable<Other>
{
    public Other Clone() { return (Other)MemberwiseClone(); }
}

public class Other : Class, ICloneable<Other>
{
    public Other Clone() { return (Other)MemberwiseClone(); }
}

最佳答案

你不能重载一个类,所以:

public class Other : Class {}
public class Other : Class, IC<Other> {}

永远不会工作。

现在,我要像 Jon Skeet 一样向您展示如何做到这一点,但随后会劝阻您不要这样做。你可以这样做:

public class CloneableOther : Class, ICloneable<Other> {  }
public class Other : CloneableOther
{

}    

public class CloneableFoo : Class, ICloneable<Foo> { }
public class Foo : CloneableFoo
{

}

这段代码所做的就是有效地从继承中删除通用参数。除了,Foo仍然可以这样做:Foo : CloneableFoo, ICloneable<Other> ,现在您必须为每个 ICloneable 创建两个类实例。

这就是为什么你首先需要这个?这是一种练习Foo : IInterface<Foo> ,但没有办法强制执行。最好的选择是复制并粘贴,并确保类(class)匹配。

也许另一种方法是在 Class 的构造函数中使用,检查 ICloneable 的类型是否是类的类型,如果不是,则抛出异常,如果它在运行时足够早地完成,那么这可能感觉像是编译时错误。

关于c# - C#中如何防止非法ICloneable<T>继承?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50458818/

相关文章:

java - 使用java和面向对象创建联系人列表

java - 泛型类型和通配符类型的区别

java - 如何创建一个以 Class 对象作为类型参数的 Java 泛型对象?

c# - RichTextBox 文本高亮显示

c++ - SFML中的White Square,Sprite和texture存储在不同的对象中

c# - 是否可以在 C# 中的运行时创建/执行代码?

javascript - 如何用函数包装 JS 库并将其放入命名空间?

java - 通过泛型参数传递时,过滤器无法访问内部对象的方法

c# - 为什么我得到 "The given path' 格式不受支持”错误

c# - 如何使用 C# 修改请求的 HTTP header ?