C# Switch on Object Type at Runtime

前端 未结 6 1165
悲&欢浪女
悲&欢浪女 2020-12-07 03:17

I have a List. I want to loop over the list and print the values out in a more friendly manner than just o.ToString() in case some of
6条回答
  •  [愿得一人]
    2020-12-07 03:43

    that depends on how important the design will be:

    • if statements or switch-statement on o.GetType()/o.GetType().Name
    • implementing a kind of IShow-Interface (with a method void Show(object o) and using a Dictionary to map types to implementations of this interface and just using
      if (TryGetValue(o.GetType, out show)) show.Show(o); 
    • just stick to it and let the objects tell the tale (override ToString) ... yes you don't want this but IMHO this is the best way to do this

提交回复
热议问题