あなたは正しい道を進んでいます - それはそれを処理する良い方法のように聞こえます. シリアル化された値と一緒に型の一意の ID を保存する必要があるため、逆シリアル化の前に ID を読み取って、デシリアライザーを正しい型に向けることができます。ID を使用する代わりに完全修飾型名を格納することもできますが、これも優れた方法です。
属性は簡単に作成できます:
class MessageAttribute : Attribute
{
public Guid ID; //assuming you want to use a GUID, could be anything
}
また、使い方も簡単です。
[Message(ID = new Guid("..."))]
class SubMessage : BaseMessage
{
}
特定のアセンブリにすべての型をロードし、それらを非常に迅速に反復処理できます。
List<Type> messageTypes = new List<Type>();
//get the assembly containing our types
Assembly messageAssembly = Assembly.Load(...);
//get all the types in the assembly
Type[] types = messageAssembly.GetTypes();
foreach(Type type in types)
{
//make sure we inherit from BaseMessage
if(type.IsAssignableFrom(typeof(BaseMessage))
{
//check to see if the inherited type has a MessageAttribute
object[] attribs = type.GetCustomAttribtues(typeof(MessageAttribute), true);
if(attribs.Length > 0)
{
messageTypes.Add(type);
}
}
}