
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Finding All Serializable Types Within an Assembly
|
771
See Also
See the “Assembly Class” and “Type Class” topics in the MSDN documentation.
13.9 Finding All Serializable Types Within
an Assembly
Problem
You need to find all the serializable types within an assembly.
Solution
Instead of testing the implemented interfaces and attributes on every type, you can
query the
Type.IsSerialized property to determine whether it is marked as serializ-
able, as the following method does:
public static Type[] GetSerializableTypes(Assembly asm)
{
List<Type> serializableTypes = new List<Type>( );
// Look at all types in the assembly.
foreach(Type type in asm.GetTypes( ))
{
if (type.IsSerializable)
{
// Add the name of the serializable type.
serializableTypes.Add(type);
}
}
return (serializableTypes.ToArray( ));
}
The GetSerializableTypes method accepts an Assembly through its asm parameter.
This assembly is searched for any serializable types, and their full names (including
namespaces) are returned in a
Type[].
In order to use this method to display the serializable types in an assembly, run the
following code:
public static void FindSerializable( )
{
Assembly asm = Assembly.GetExecutingAssembly( );
Type[] serializable = GetSerializableTypes(asm);
// Write out the serializable types in the assembly.
if(serializable.Length ...