[C# code]
private CustomClass(SerializationInfo serInfo, StreamingContext context) {
_intData = TypeSafeSerializer.GetValue<int>("_intData", serInfo);
_stringData = TypeSafeSerializer.GetValue<string>("_stringData", serInfo);
_genericData = TypeSafeSerializer.GetValue<T>("_genericData", serInfo);
}
public void GetObjectData(SerializationInfo serInfo, StreamingContext context) {
TypeSafeSerializer.AddValue<int>("_intData", _intData, serInfo);
TypeSafeSerializer.AddValue<string>("_stringData", _stringData, serInfo);
TypeSafeSerializer.AddValue<T>("_genericData", _genericData, serInfo);
}
For the
AddValue()
method, you can see how your generic data type now participates on equal footing
with its non-generic counterparts. It no longer requires a separate call to acquire its types. The real bene-
factor here, though, is
GetValue()
. The generic
GetValue()
method of the
TypeSafeSerializer
class lets you extract the serialized values for generic and non-generic types without any casting. For
both of these cases, the type of the incoming type parameter ends up driving which underlying method
of
SerializationInfo
gets called, which means there's no need for a series of methods that are over-
loaded on type.
This example should illustrate how custom types are serialized and how generics can be applied to make
the serialization a more type-safe experience. This pattern may also help you identify similar scenarios
where generics can be leveraged to improve your existing classes.
Serialization with Web Services
Whenever you're working with web services, you must consider how types will be transported to and
from a service. And, with the introduction of generics, you must also consider how generic types will
participate in your web service APIs. Specifically, you'll need to think about how a Web service will seri-
alize each generic type and transform it into a type that can be represented in a SOAP construct.
In this section you'll create a simple web service that includes references to a few generic types to demon-
strate how a generic type will be brokered by a service. The following code represents the implementation
of a basic web service:
[VB code]
<WebServiceBinding(ConformanceClaims:=WsiClaims.BP10,EmitConformanceClaims:=True)>_
Public Class SampleService
<XmlType("My{T}List")> _
Public Class MyList(Of T)
Inherits List(Of T)
End Class
<XmlType("My{T}Collection")> _
Public Class MyCollection(Of T)
Inherits Collection(Of T)
End Class
<WebMethod()> _
Public Function GetListValues1() As MyList(Of String)
Dim list As New MyList(Of String)
208
Chapter 9
12_559885 ch09.qxd 9/8/05 11:04 PM Page 208