为什么在System.Object的定义MemberwiseClone是受保护的?它为什么不公开? [英] why MemberwiseClone defined in System.Object is protected? why it's not public?

查看:108
本文介绍了为什么在System.Object的定义MemberwiseClone是受保护的?它为什么不公开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道为什么MemberwiseClone被定义为受保护。这意味着只有派生类型可以访问它。有什么问题,如果它被定义公开?

I'm wondering why MemberwiseClone is defined as protected. this means that only derived types can access it. what is the problem if it was defined public?

推荐答案

<一个href="http://stackoverflow.com/questions/1308803/why-is-cloning-in-net-so-difficult/1308863#1308863">Pavel Minaev的从另一个讨论的答案:

其他人已经解释了关于MemberwiseClone,但没有人给的,为什么它是受保护的解释。我会尽力给的理由。

Others have already explained about MemberwiseClone, but no-one gave the explanation of why it is protected. I'll try to give the rationale.

这里的问题是,MemberwiseClone只是一味的复制状态。在许多情况下,这是不希望的。例如,对象可能有一个私有字段是一个引用列表。浅表副本,比如什么MemberwiseClone做,将导致新的对象指向同一列表 - 和类可能被写入没想到列表与其他人共享

The problem here is that MemberwiseClone just blindly copies the state. In many cases, this is undesirable. For example, the object might have a private field which is a reference to a List. A shallow copy, such as what MemberwiseClone does, would result in new object pointing to the same list - and the class may well be written not expecting the list to be shared with anyone else.

或对象可以有某种ID字段,在构造函数中产生的 - 同样,在克隆的是,你会得到两个对象具有相同的ID,这可能会导致各种奇怪的故障的方法假设ID是唯一的

Or an object can have some sort of ID field, generated in constructor - again, when you clone that, you get two objects with the same ID, which may lead to all kinds of weird failures in methods assuming that ID is unique.

或者说你打开一个套接字或文件流,并存储一个引用的对象。 MemberwiseClone将刚才复制的参考 - 你能想象这两个对象试图交织调用同一个流是不会有好下场

Or say you have an object that opens a socket or a file stream, and stores a reference to that. MemberwiseClone will just copy the reference - and you can imagine that two objects trying to interleave calls to the same stream isn't going to end well.

在总之,克隆,是不明确定义的任意的对象的操作。该成员逐一运算符=在C ++中提供的所有类默认情况下,其实更多的是一种讨厌的,因为常常人们忘记了它的存在,并没有禁用它的类,因为复制没有意义,或者是危险的(也有令人惊讶的很多这样的类)。

In short, "cloning" is not a well-defined operation for arbitrary objects. The fact that memberwise operator= is provided for all classes by default in C++ is more of a nuisance, as all too often people forget that it's there, and do not disable it for classes for which copying doesn't make sense, or is dangerous (and there are surprisingly many such classes).

这篇关于为什么在System.Object的定义MemberwiseClone是受保护的?它为什么不公开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆