为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

C#
狐的传说 2021-06-24 18:02:33
我有一个界面:public interface ICloneable<out T>    where T : ICloneable<T>{    T Clone();}应该接收实现此接口的类型(如下所示)。我可以创建一个实现它的类:public class Class : ICloneable<Class>{    public Class Clone() { return (Class)MemberwiseClone(); }}伟大的 !但是任何人都可以创建一个实现 ICloneable<T> “错误”的类。是否存在防止继承的方法,如下所示?(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(); }}
查看完整描述

1 回答

?
www说

TA贡献1775条经验 获得超8个赞

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


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的类型,如果不是则抛出异常,这可能会让人感觉像是编译时错误,如果它在运行时完成得足够早。



查看完整回答
反对 回复 2021-06-27
  • 1 回答
  • 0 关注
  • 168 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信