說我有以下類:DataContractJsonSerializer拋出SerializationException,抱怨意想不到的類型,即使我已經與KnownTypeAttribute
[DataContract]
class Entry<T>
{
[DataMember]
public T Data { get; set; }
}
[DataContract]
class DataList<T>
{
[DataMember]
public IList<T> Collection { get; set; }
}
[DataContract]
[KnownType(typeof(User))]
class ExtendedDataList : DataList<object>
{
[DataMember]
public string SomeExtraParameter { get; set; }
}
[DataContract]
class User
{
[DataMember]
public string Name { get; set; }
}
我申請KnownTypeAttribute
到ExtendedDataList
因爲那類擴展的基類的一般鍵入object
,它將在列表中存儲不同種類的對象。在這個例子中,我已經標記了一個已知類型User
,因爲我知道它將包含User
對象。
這裏的序列化代碼:
var user = new User { Name = "Bob" };
var users = new ExtendedDataList { Collection = new List<object> { user } };
serialize(users);
與
static void serialize<T>(T obj)
{
var entry = new Entry<T>();
entry.Data = obj;
var stream = new MemoryStream();
var serializer = new DataContractJsonSerializer(typeof(Entry<T>));
serializer.WriteObject(stream, entry);
stream.Seek(0, SeekOrigin.Begin);
var r = new StreamReader(stream);
var s = r.ReadToEnd();
System.Diagnostics.Debug.WriteLine(s);
}
行serializer.WriteObject(stream, entry);
拋出一個SerializationException
說,類型User
是沒有預料,我應該用KnownTypeAttribute
指定它。但我做了(間接)!
我該如何做這項工作?我不能將KnownType
移動到Entry<T>
類,因爲它需要是一般的。爲什麼DataContractJsonSerializer
看不到ExtendedDataList
指定User
作爲已知類型?