C# Beginners Tutorial - 199 - ICloneable

preview_player
Показать описание
Рекомендации по теме
Комментарии
Автор

This won't make a clone, this will result in a referenced object, so an update to one will still update the other...

NathanRover
Автор

Plain and simple: When you have reference types (ones that are derived from System.Object Class) within your class that points to an object in memory just create new object of your class with new objects. If it only contains value types (ones that are derived from System.ValueType class; structs: int, double, byte etc.) just return this.MemberwiseClone();

PrfixProducts
Автор

So you should create a new object of Myclass

public MyClass Clone()
{
MyClass a = new MyClass();
a.Name = this.Name;
return a;
}

treasure
Автор

Ok, so I'm having a little trouble understanding what's going on here. The clone method returns the exact value of the referenced object, but wouldn't assigning the old object to the new object do the same thing? For example, I declare a CoolObject class with CoolObject co = new CoolObject(string value); Wouldn't CoolObject anotherco = co; do the same thing as CoolObject anotherco = co.Clone();? The part that is throwing me off is @Nathan Rover says that modifying a value in the cloned object will also modify the value of the original object? I could use a little clarification, thanks.

hidronoob