我在引用和对象克隆方面遇到了一个奇怪的问题,我无法解决。我有一个由属性名称组成的类 MyClass。我还有我的自定义用户控件,它有一个 MyClass 类型的属性 - myclassproperty。这些控件放置在窗体上。如果我单击其中一个控件,则会出现一个新表单。我将一个参数传递给新形式 - myclassproperty
NewForm form = new NewForm(myusercontrol.myclassproperty)
this.myclassproperty = myclassproperty;
clonedproperty = ObjectCloner.Clone(myclassproperty);
clonedproperty 是一个克隆对象。对于克隆,我使用此代码,我在 stackoverflow 上找到了
public static class ObjectCloner
{
/// <summary>
/// Reference Article http://www.codeproject.com/KB/tips/SerializedObjectCloner.aspx
///
/// Provides a method for performing a deep copy of an object.
/// Binary Serialization is used to perform the copy.
/// </summary>
/// <summary>
/// Perform a deep Copy of the object.
/// </summary>
/// <typeparam name="T">The type of object being copied.</typeparam>
/// <param name="source">The object instance to copy.</param>
/// <returns>The copied object.</returns>
public static T Clone<T>(T source)
{
if (!typeof(T).IsSerializable)
{
throw new ArgumentException("The type must be serializable.", "source");
}
// Don't serialize a null object, simply return the default for that object
if (Object.ReferenceEquals(source, null))
{
return default(T);
}
IFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream();
using (stream)
{
formatter.Serialize(stream, source);
stream.Seek(0, SeekOrigin.Begin);
return (T)formatter.Deserialize(stream);
}
}
}
}
在新表单中,我有一个文本框,它绑定到对象 clonedproperty 中的归档名称
txtName.DataBindings.Add("文本", clonedproperty, "名称");
我的表单上还有两个按钮“保存”和“取消”。如果我点击取消,表单只是关闭,但如果我点击保存,我会这样做
this.myclassproperty = clonedproperty
表格关闭。
在我看来,此时 myusercontrol.myclassproperty 是对 clonedproperty 的引用,所以如果我再次单击 myusercontrol 新值(我之前输入的)会显示。
但是我一直都有旧的价值:(