浅度复制
// See https://aka.ms/new-console-template for more information
//Console.WriteLine("Hello, World!"); 2024.3.4
using System;
using System.Collections.Generic;
using System.Text;
namespace shallowCopyDemo1
{
public class Content
{
public int Val;
}
public class Cloner
{
public Content MyContent = new Content();
public Cloner(int newVal)
{
MyContent.Val = newVal;
}
public object GetCopy()
{
return MemberwiseClone();
}
}
public class Program
{
static void Main(string[] args)
{
Cloner mySource = new Cloner(5);
Cloner myTarget = (Cloner)mySource.GetCopy();
Console.WriteLine("MyTarget.MyContent.val = {0}", myTarget.MyContent.Val);
mySource.MyContent.Val = 2;
Console.WriteLine("MyTarget.MyContent.val = {0}", myTarget.MyContent.Val);
Console.ReadKey();
}
}
}
/*
MyTarget.MyContent.val = 5
MyTarget.MyContent.val = 2
*/
深度复制
// See https://aka.ms/new-console-template for more information
//Console.WriteLine("Hello, World!"); 2024.3.4
using System;
using System.Collections.Generic;
using System.Text;
namespace DeepCopyDemo01
{
public class Content
{
public int Val;
}
public class Cloner : ICloneable
{
public Content MyContent = new Content();
public Cloner(int newVal)
{
MyContent.Val = newVal;
}
public object GetCopy()
{
return MemberwiseClone();
}
#region ICloneable 成员
public object Clone()
{
Cloner clonedCloner = new Cloner(MyContent.Val);
return clonedCloner;
}
#endregion
}
public class Program
{
static void Main(string[] args)
{
Cloner mySource = new Cloner(5);
Cloner myTarget = (Cloner)mySource.Clone();
Console.WriteLine("MyTarget.MyContent.val = {0}", myTarget.MyContent.Val);
mySource.MyContent.Val = 2;
Console.WriteLine("MyTarget.MyContent.val = {0}", myTarget.MyContent.Val);
Console.ReadKey();
}
}
}
/*
MyTarget.MyContent.val = 5
MyTarget.MyContent.val = 5
*/
标签:MyTarget,Console,Val,c#,浅度,复制,MyContent,Cloner,public From: https://www.cnblogs.com/QHMG/p/18051624