如何通过NetDataContractSerializer测试Serializable?

时间:2012-07-24 14:24:14

标签: .net generics serialization netdatacontractserializer

有没有办法在代码中测试NetDataContractSerializer的类型是否可序列化?我正在编写一个在内部使用NetDataContractSerializer的泛型类,如果尝试将其与无法处理的类型一起使用,则希望在构造函数中抛出异常。

1 个答案:

答案 0 :(得分:0)

这是我到目前为止所发现的。有更简单的方法吗?

Private Sub ConfirmTypeIsNetDataContractSerializable(type As Type)
    Dim specialAllowedTypes As Type() = {GetType(Decimal), GetType(String), _
   GetType(DateTime), GetType(DateTimeOffset), GetType(TimeSpan), _
   GetType(Guid), GetType(Uri), GetType(XmlQualifiedName), GetType(XmlElement), GetType(XmlNode)}
    If type.IsPrimitive() OrElse specialAllowedTypes.Contains(type) Then Return

    If type.IsDefined(GetType(DataContractAttribute), inherit:=False) Then Return
    If type.IsDefined(GetType(SerializableAttribute), inherit:=False) Then Return
    If type.IsEnum Then Return
    If type.GetInterfaces().Contains(GetType(IXmlSerializable)) Then Return

    Dim serializer As New NetDataContractSerializer
    Using dummyStream As New System.IO.MemoryStream()
        serializer.Serialize(dummyStream, Activator.CreateInstance(type)) ' throws exception if not serializable
    End Using
End Sub