我有一个类,它是我的Windows8.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>发布于 2015-06-09 16:57:25
如果您将DataDictionary属性的设置程序从“私有”更改为“公共”,那么它应该可以按预期工作。
https://stackoverflow.com/questions/30734964
复制相似问题