【发布时间】:2018-10-31 16:46:20
【问题描述】:
我有一个界面:
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(); }
}
【问题讨论】:
-
您只是在寻找sealed吗?
-
@leofun01这没有回答为什么。这回答了什么。
-
所以您问是否有可能任何类都可以仅使用自身作为参数来实现接口?所以
class Foo : ICloneable<Bar>行不通,它必须 是class Foo : ICloneable<Foo>? -
@leofun01 - 语言不支持这个。你只需要在实现你的类时小心。
-
由于您的
Class、Other类和ICloneable接口是公开的,因此任何开发人员都可以随心所欲地使用它。你可以告诉用户你的类应该做什么(描述接口),但你不能告诉他们如何实现它。此外,我个人仍然看不到此功能有任何可能的适用性。
标签: c# oop generics inheritance inheritance-prevention