これは、「Watson et al: Beginning Visual C# Chapter 10: 演習 4」に関連しています: People クラスに ICloneable インターフェイスを実装して、ディープ コピー機能を提供する
class People : DictionaryBase: ICloneable
public void DictAdd(Person newPerson)
{
Dictionary.Add(newPerson.Name, newPerson);
public object Clone()
{
People newPeople = new People();
foreach (Person myPerson in Dictionary.Values)
{
Person ClonePerson = (Person)myPerson.Clone();
newPeople.DictAdd(ClonePerson);
}
return newPeople;
}
Person クラスには次のものがあります。
public object Clone()
{
Person newPerson = new Person();
newPerson = (Person)newPerson.MemberwiseClone();
newPerson.Age = age;
newPerson.Name = name;
return newPerson;
}
Program.cs でテストするには:
People clonedPeople = (People)PeopleCollection.Clone();
PeopleCollection.Remove("Mick");
myPerson1.Name = "Jock";
myPerson1.Age = 13;
PeopleCollection.DictAdd(myPerson1);
Console.WriteLine("In the current collection \"Mick\" is now: \"{0}\" and his age is: {1}", myPerson1.Name, myPerson1.Age);
Console.WriteLine("But \"Mick\" should remain in the original collection, now cloned.");
foreach (DictionaryEntry p in clonedPeople)
{
Console.WriteLine();
Console.WriteLine("myPerson Name: {0} myPerson.Age: {1}", ((Person)p.Value).Name, ((Person)p.Value).Age);
}
これは機能し、「Mick」の元の値が保持されます。しかし問題は、そもそも Person と People クラスに ":ICloneable" を実装するところまでです。コードは、それがあってもなくても同じように機能します。
関連する質問は、彼らの例で ICloneable の「再帰的」実装を実行することの有効性です。
public class Content
{
public int Val;
}
public class Cloner: ICloneable
{
public Content MyContent = new Content();
public Cloner(int newVal)
{
MyContent.Val = newVal;
}
public object Clone()
{
Cloner clonedCloner = new Cloner(MyContent.Val);
return clonedCloner;
}
}
この再帰を機能させるために惨めに試みましたが、最終的には StackOverflow になります。グローバル/静的変数を使用してループを終了する以外に、これを「再帰的に」実装するエレガントな方法はありますか?