MemberwiseClone()的方法是做什么的? [英] What is the method MemberwiseClone() doing?
问题描述
我对下面的代码感到困惑,
I am confused with this code below,
Developer devCopy = (Developer)dev.Clone();
Developer类的克隆方法只是创建一个Employee克隆,然后开发人员如何获得另一个开发人员克隆。
Clone method of Developer class just creating a Employee clone, then how developer get another clone of developer.
public abstract class Employee
{
public abstract Employee Clone();
public string Name { get; set; }
public string Role { get; set; }
}
public class Typist : Employee
{
public int WordsPerMinute { get; set; }
public override Employee Clone()
{
return (Employee)MemberwiseClone();
}
public override string ToString()
{
return string.Format("{0} - {1} - {2}wpm", Name, Role, WordsPerMinute);
}
}
public class Developer : Employee
{
public string PreferredLanguage { get; set; }
public override Employee Clone()
{
return (Employee)MemberwiseClone();
}
public override string ToString()
{
return string.Format("{0} - {1} - {2}", Name, Role, PreferredLanguage);
}
}
Developer dev = new Developer();
dev.Name = "Bob";
dev.Role = "Team Leader";
dev.PreferredLanguage = "C#";
Developer devCopy = (Developer)dev.Clone();
devCopy.Name = "Sue";
Console.WriteLine(dev);
Console.WriteLine(devCopy);
/* OUTPUT
Bob - Team Leader - C#
Sue - Team Leader - C#
*/
Typist typist = new Typist();
typist.Name = "Kay";
typist.Role = "Typist";
typist.WordsPerMinute = 120;
Typist typistCopy = (Typist)typist.Clone();
typistCopy.Name = "Tim";
typistCopy.WordsPerMinute = 115;
Console.WriteLine(typist);
Console.WriteLine(typistCopy);
/* OUTPUT
Kay - Typist - 120wpm
Tim - Typist - 115wpm
*/
推荐答案
因为方法 MemberwiseClone()
正在为您执行此操作。请参见文档
Because the method MemberwiseClone()
is doing this for you. See the documentation
MemberwiseClone方法通过创建新对象,然后将当前对象的非静态字段复制到新对象来创建浅表副本。如果字段是值类型,则将执行该字段的逐位复制。如果字段是引用类型,则引用被复制,但引用的对象则不是。因此,原始对象及其克隆引用的是同一对象。
The MemberwiseClone method creates a shallow copy by creating a new object, and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, the reference is copied but the referred object is not; therefore, the original object and its clone refer to the same object.
每当您看到不理解的方法时,都可以跟踪谁声明了它(我想是在Visual Studio中),然后查看其文档。在大多数情况下,这使事情变得显而易见。
Whenever you see a method you don't unerstand, you can trace who has declared it (in Visual Studio, I guess), and in turn see its documentation. That makes things pretty obvious most of the time.
这篇关于MemberwiseClone()的方法是做什么的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!