我不知道如何通過DataContractSerialize序列化對象。 這裏是我的代碼:爲什麼DataContractSerializer不起作用?
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);
它會拋出一個異常。我能做什麼?
什麼是例外? – mgnoonan 2012-04-20 01:08:50
它需要KnowType 類型'System.RuntimeType'與數據協定名稱'RuntimeType:http://schemas.datacontract.org/2004/07/System'不是預期的。將任何未知的靜態類型添加到已知類型列表中 - 例如,使用KnownTypeAttribute屬性或將它們添加到傳遞給DataContractSerializer的已知類型列表中。 – GeminiYellow 2012-04-20 01:11:44