我不知道如何通过 DataContractSerialize 序列化对象。这是我的代码:
public static string DataContractSerialize(object target)
{
var formatter = new DataContractSerializer(target.GetType());
using (var stream = new MemoryStream())
{
formatter.WriteObject(stream, target);
stream.Position = 0;
return Encoding.UTF8.GetString(stream.ToArray());
}
}
和实体
[Serializable, DataContract(Namespace = "CommunicationModel.Entity")]
[KnownType(typeof(Message))]
[KnownType(typeof(int))]
[KnownType(typeof(string))]
[KnownType(typeof(Type))]
[KnownType(typeof(object))]
public class Message : IDisposable
{
public Message(string stringInfo)
{
MessageValue = stringInfo;
MessageType = typeof (string);
}
public Message(int intInfo)
{
MessageValue = intInfo;
MessageType = typeof (int);
}
[DataMember]
public Type MessageType { get; private set; }
[DataMember]
public object MessageValue { get; private set; }
#region Implementation of IDisposable
public void Dispose()
{
}
#endregion
}
当我像这样运行 DataContractSerialize 时:
var sData = SerializerHelper.DataContractSerialize(msg);
它会抛出异常。我能做些什么?