Originally Posted by
Hyle
Serializable shows up in the assembly as an interface in a declaration, not as an attribute (for example, when you view in ildasm). So, .NET dummies it up somehow to let you retrieve it as an attribute. There are other such anomolies.
Eh, not really. There is the SerializableAttribute attribute and ISerializable interface. Both are independent of each other; classes can implement either one, neither, or both (although it's pretty useless to implement ISerializable and not mark the class with the Serializable attribute). Consider the following example:
Code:
using System;
using System.Collections;
using System.Runtime.Serialization;
namespace Test2005Library
{
//The Serializable attribute is attached to this class
[Author("Joe Bob")]
public class BaseTemplate<T>
where T : IEnumerable
{
}
//Implements ISerializable
public class A : ISerializable
{
#region ISerializable Members
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
//The Serializable attribute is attached to this class
//Implements ISerializable
[Serializable]
public class B : ISerializable
{
#region ISerializable Members
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new Exception("The method or operation is not implemented.");
}
#endregion
}
}
Code:
using System;
using System.Collections;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.Serialization;
//Make sure to reference Test2005Attribute.
//Make sure NOT to reference Test2005Library.
namespace Test2005
{
class Program
{
static void Main(string[] args)
{
string path = ""; //put the full path to Test2005Library.dll here
Assembly assembly = Assembly.LoadFile(path);
foreach (Type type in assembly.GetTypes())
{
object[] attributes = type.GetCustomAttributes (true);
foreach (object obj in attributes)
{
SerializableAttribute serialAttribute =
obj as SerializableAttribute;
if (serialAttribute != null)
{
Console.WriteLine("{0} has the Serializable attribute",
type);
}
}
object[] interfaces = type.GetInterfaces();
foreach (Type obj in interfaces)
{
ISerializable serializableObj = obj as ISerializable;
if (serializableObj != null)
{
Console.WriteLine("{0} implements ISerializable",
type);
}
}
}
Console.WriteLine("Finished");
Console.ReadLine();
}
}
}
Output:
Code:
Test2005Library.BaseTemplate`1[T] has the Serializable attribute
Test2005Library.A implements ISerializable
Test2005Library.B has the Serializable attribute
Test2005Library.B implements ISerializable
Finished