我有一个类是Windows 8.1通用应用程序的视图模型。我希望能够根据需要序列化/反序列化此类。除了IDictionary
公共财产之外,我有这个工作。此属性正在跳过。当我明确告诉DataContractSerializer
自行序列化时,它会按预期工作。
序列化视图模型类时,为什么DataContractSerializer
没有拾取它?当我直接序列化KnowType
时,我已经解决了所有DataDictionary
个问题。
这是有问题的课程
[KnownType( typeof( ViewModel ) )]
public class AViewModel : ViewModelBase
{
public ViewModel()
{
DataDictionary = new Dictionary<double, IData>();
SaveCommand = new RelayCommand( () => Save() );
LoadCommand = new RelayCommand( () => Load() );
}
private string _firstName;
public string FirstName { get { return _firstName; } set { Set( () => FirstName, ref _firstName, value ); } }
private string _lastName;
public string LastName { get { return _lastName; } set { Set( () => LastName, ref _lastName, value ); } }
private IDictionary<double, IData> _dataDictionary;
public IDictionary<double, IData> DataDictionary { get { return _dataDictionary; } private set { _dataDictionary = value; } }
public ICommand SaveCommand { get; private set; }
public ICommand LoadCommand { get; private set; }
private async void Save()
{
//logic will go here, example in unit test below
}
}
以下是与IData
public interface IData
{
string Type { get; set; }
}
[KnownType( typeof( BlueData ) )]
public class BlueData : IData
{
public string String1 { get; set; }
public string Type { get; set; }
}
[KnownType( typeof( GreenData ) )]
public class GreenData : IData
{
public string Type { get; set; }
public string String1 { get; set; }
}
以下是我用来构建序列化的代码
ViewModel model = new ViewModel();
model.FirstName = "First";
model.LastName = "Last";
model.DataDictionary.Add( 1.2, new BlueData { String1 = "TestBlueData", Type = "BlueData" } );
MemoryStream memoryStream = new MemoryStream();
DataContractSerializer serializer = new DataContractSerializer( typeof( ViewModel ) );
serializer.WriteObject( memoryStream, model );
memoryStream.Seek( 0, SeekOrigin.Begin );
string xml;
using ( StreamReader reader = new StreamReader( memoryStream ) )
{
xml = reader.ReadToEnd();
}
这是我从上面的代码
获得的xml输出<ViewModel xmlns="http://schemas.datacontract.org/2004/07/ApplicationNamespace.ViewModel" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><FirstName>First</FirstName><LastName>Last</LastName></ViewModel>
当我直接在DataContractSerializer
上致电model.DataDictionary
时,我会收到以下内容
<ArrayOfKeyValueOfdoubleanyType xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns:i="http://www.w3.org/2001/XMLSchema-instance"><KeyValueOfdoubleanyType><Key>1.2</Key><Value i:type="a:BlueData" xmlns:a="http://schemas.datacontract.org/2004/07/ApplicationNamespace"><a:String1>TestBlueData</a:String1><a:Type>BlueData</a:Type></Value></KeyValueOfdoubleanyType></ArrayOfKeyValueOfdoubleanyType>
答案 0 :(得分:1)
如果您将DataDictionary属性的setter从“private”更改为“public”,那么它应该按预期工作