views:

79

answers:

1

I have a bunch of stored, serialized classes (that all inherit from a base class) in C#. Along with the serialized class, I also store an enum value that identifies the which subclass is serialized.

This means that whenever I want to serialize/deserialize the class, I've got to use a couple of big switch statements based on the enum to decide which subclass to deserialize into. It seems like there would be a be a way to do it using some kind of structuremap-like thing. (Its for a widget/dashboard, so its completely possible that many more subclasses will appear in the future).

Right now, It looks like this...

 widget = DeserializeFromDb(GetWidgetType(widgetrow.WidgetType),  widgetRow.serializedWidget);

   private HtmlWidget DeserializeFromDb(WidgetType type, string serialized)
   {
        Basics.Serial.IStringSerializer serializer = Basics.Serial.BinarySerializer.GetInstance();

        switch (type)
        {
            case WidgetType.AbstractBase:
                return serializer.Deserialize<HtmlWidget>(serialized);
                break;
            case WidgetType.Widget1:
                return serializer.Deserialize<Widget1>(serialized);
                break;
            case WidgetType.Widget2:
                return serializer.Deserialize<Widget2>(serialized);
                break;
       }
  }
+5  A: 

You can map enum values to Func<ISerializer, string, HtmlWidget> delegates:

static Dictionary<WidgetType, Func<ISerializer, string, HtmlWidget>> map = 
   new Dictionary<WidgetType, Func<ISerializer, string, HtmlWidget>> {
      { WidgetType.AbstractBase, (s, o) => s.Deserialize<HtmlWidget>(o) },
      { WidgetType.Widget1, (s, o) => s.Deserialize<Widget1>(o) }, 
   // ...
};

// use it like:
return map[type](serializer, serialized);
Mehrdad Afshari