我有一个接口:
public interface ICloneable<out T>
where T : ICloneable<T>
{
T Clone();
}它应该接收实现此接口的类型(如下所示)。
我可以创建一个实现它的类:
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(); }
}发布于 2018-05-22 03:05:15
不能重载一个类,所以:
public class Other : Class {}
public class Other : Class, IC<Other> {}永远不会起作用。
现在,我要拉一个乔恩·斯基特,向你展示你是如何做到的,但又不鼓励你这么做。你可以这样做:
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的构造函数中进行检查,查看ICloneable的类型是否是类的类型,如果不是,则抛出异常,如果在运行时执行得足够早,那么排序可能会感觉像是编译时错误。
https://stackoverflow.com/questions/50458818
复制相似问题