C#.NET 中 liskov 原理的类型参数约束
我尝试创建一个继承 System.ICloneable 接口的通用接口,但 Clone() 方法的返回类型是 T。当然,T 类型需要约束以确保它是 System.Object 类的继承,但是以下代码不起作用。
public interface ICloneable<T> : System.ICloneable where T : object {
T Clone ();
}
我究竟做错了什么?
另外,以下约束不起作用:
- where T : System.Object
- where T : class
在这种情况下如何使用里氏原则,即可以缩小返回类型来解决此问题?
PS:如果我犯了错误,请原谅我的英语。 我的母语不是英语。
I try to create a generic interface that inherits the System.ICloneable interface but where the returntype of the Clone()-method is T. Of course the T-type needs constraints to be sure it's an inheritance of the System.Object-class but the following code is not working.
public interface ICloneable<T> : System.ICloneable where T : object {
T Clone ();
}
What am I doing wrong?
Also the following constraints don't work:
- where T : System.Object
- where T : class
how can I use the Liskov-principle in this case that says that you can narrow your return type, to solve this problem?
P.S.: Sorry for my English, if i made mistakes. I'm not a native English speaker.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么你需要约束? 一切都继承自
object
...如果没有限制,您的代码应该可以工作,但您需要以与
IEnumerable
相同的方式实现两个Clone
方法>/IEnumerable
工作 - .NET 没有协变返回类型。 然后,您还应该指定您的Clone
方法隐藏了ICloneable
中的方法:请注意,当前的
ICloneable
接口在某种程度上已被弃用 - 因为它给出了没有表明克隆的深度,在大多数情况下它并不是很有用。您真的需要扩展非泛型类型吗? 您是否希望用户像使用通用界面一样使用非通用界面?
Why do you need a constraint at all? Everything inherits from
object
...Without the constraint your code should work but you'll need to implement both
Clone
methods in the same way asIEnumerable
/IEnumerable<T>
work - .NET doesn't have covariant return types. You should also then specify that yourClone
method is hiding the one inICloneable
:Note that the current
ICloneable
interface is somewhat deprecated - because it gives no indication of the depth of cloning, it's not terribly useful in most cases.Do you really need to extend the non-generic type at all? Do you expect users to want to use the non-generic interface as well as your generic one?