For C #, it is very simple to check which object.MemberwiseClone does in terms of constructors:
class Program { class A : ICloneable { public int X = 2; public A() { Console.WriteLine("hiya"); X = 1; } public object Clone() { A a = MemberwiseClone() as A; return a; } } static void Main(string[] args) { A a = new A(); aX = 3; A b = a.Clone() as A; } }
Place a breakpoint in the constructor. It is called once for the above program. And if you think about it, Clone in the base class cannot call the constructor:
- What is he going to build? This can reflect and get the maximum derived type.
- But what if this type does not have a constructor publicly accessible without parameters?
- Whether it can call a private or protected constructor, and expect the object to be initialized correctly.
The standard implementation of MemberWiseClone should depend on the initialization of the lower level type, and not on the design. An alternative would be difficult to implement, difficult to understand and find the source of errors.
source share