Como promprobar si un Type es serializable:
Como comprobar si un objeto es serializable:
Ejemplo de sintaxis para una condicional de .Net Framework del proyecto.
Código (vbnet) [Seleccionar]
' Is Type Serializable?
' By Elektro
'
' Usage Examples:
'
'MsgBox(IsTypeSerializable(Of String))
'MsgBox(IsTypeSerializable(GetType(Form)))
'MsgBox(IsTypeSerializable(0.0F.GetType))
'
''' <summary>
''' Determines whether a Type can be serialized.
''' </summary>
''' <typeparam name="T"></typeparam>
''' <returns><c>true</c> if Type can be serialized; otherwise, <c>false</c>.</returns>
Private Function IsTypeSerializable(Of T)() As Boolean
Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))
End Function
''' <summary>
''' Determines whether a Type can be serialized.
''' </summary>
''' <typeparam name="T"></typeparam>
''' <param name="Type">The Type.</param>
''' <returns><c>true</c> if Type can be serialized; otherwise, <c>false</c>.</returns>
Private Function IsTypeSerializable(Of T)(ByVal Type As T) As Boolean
Return Attribute.IsDefined(GetType(T), GetType(SerializableAttribute))
End Function
Como comprobar si un objeto es serializable:
Código (vbnet) [Seleccionar]
' Is Object Serializable?
' By Elektro
'
' Usage Examples:
'
'MsgBox(IsObjectSerializable(New ArrayList From {"String Item"}, SerializationFormat.Xml)) ' Result: True
'MsgBox(IsObjectSerializable(New ArrayList From {New Object() {"Collection", "Of", "Strings"}})) ' Result: False
'
''' <summary>
''' Determines whether an object can be serialized.
''' </summary>
''' <param name="Object">The object.</param>
''' <returns><c>true</c> if object can be serialized; otherwise, <c>false</c>.</returns>
Private Function IsObjectSerializable(ByVal [Object] As Object,
Optional ByVal SerializationFormat As SerializationFormat =
SerializationFormat.Xml) As Boolean
Dim Serializer As Object
Using fs As New IO.MemoryStream
Select Case SerializationFormat
Case Data.SerializationFormat.Binary
Serializer = New Runtime.Serialization.Formatters.Binary.BinaryFormatter()
Case Data.SerializationFormat.Xml
Serializer = New Xml.Serialization.XmlSerializer([Object].GetType)
Case Else
Throw New ArgumentException("Invalid SerializationFormat", SerializationFormat)
End Select
Try
Serializer.Serialize(fs, [Object])
Return True
Catch ex As InvalidOperationException
Return False
End Try
End Using ' fs As New MemoryStream
End Function
Ejemplo de sintaxis para una condicional de .Net Framework del proyecto.
Código (vbnet) [Seleccionar]
#If NET20 Then
' This happens when the app targets .NEt Framework 2.0
#ElseIf NET40 Then
' This happens when the app targets .NEt Framework 4.0
#End If