我对引用和对象克隆有一个奇怪的问题,我无法解决。 我有一个MyClass类,它由属性Name组成。我也有我的custon用户控件,它具有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(“Text”,clonedproperty,“Name”);
我的表单上还有两个按钮''save''和''cancel''。如果我单击取消,表单只是关闭,但如果我点击保存我就像那样
this.myclassproperty = clonedproperty
表格已关闭。
在我看来,此时myusercontrol.myclassproperty是对clonedproperty的引用,所以如果我再次点击myusercontrol,则会显示新值(我之前输入的)。
但是我一直都有旧价值:(
答案 0 :(得分:0)
没有其他任何东西继续下去,我会说表单可能正在使用该对象并进行更改,然后进行克隆。首先尝试克隆然后打开这样的表单。
clonedproperty = ObjectCloner.Clone(myclassproperty); NewForm form = new NewForm(myusercontrol.myclassproperty) this.myclassproperty = myclassproperty;
如果这不起作用,您可以发布调用表单代码吗?