我有一个界面:
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/