我想合并两个模型对象,使得新对象中的非空字段更新旧对象的字段。但我这样做了Invalid cross thread access
。这就是我在做的事情:
我在BaseJson
命名空间中有User
和Application.Models
个类:
的 BaseJson
[DataContract]
public class BaseJson
{
public void MergeFrom(BaseJson baseJson)
{
if (baseJson != null)
{
try
{
// http://stackoverflow.com/questions/8702603/merging-two-objects-in-c-sharp
//Type t = typeof();
var Properties = baseJson.GetType().GetProperties();
//var properties = t.GetProperties();//.Where(prop => prop.CanRead && prop.CanWrite);
foreach (var Property in Properties)
{
var value = Property.GetValue(baseJson, null);
if (value != null)
Property.SetValue(this, value, null);
}
}
catch
{
throw new Exception("Error Merging.");
}
}
}
}
用户
public class User : BaseJson, INotifyPropertyChanged
{
private string _uid;
[DataMember(Name="uid")]
public string Uid
{
get { return this._uid; }
set { SetField(ref _uid, value, "Uid"); }
}
// Other similar properties
private void SetField<T>(ref T field, T value, string memberName=null)
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
RaisePropertyChanged(memberName);
}
App.GetUserManager().SaveUserLocally(this);
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (this.PropertyChanged != null)
{
// gives invalid cross thread access error here
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
对于两个用户对象u1和u2,我正在调用
u1.MergeFrom(u2)
来自不同班级ViewModel.cs
的。
我的问题是,有时它不会给出任何错误,但对于其他人,它会在Invalid cross thread access
方法中提供RaisePropertyChanged
。