C# Switch on Object Type at Runtime

前端 未结 6 1170
悲&欢浪女
悲&欢浪女 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:44

    Somthing like this might get you on the way:

    private static String MyToString(object o)
    {
        var val = "";
        switch (o.GetType().Name)
        {
            case "Boolean": val = ((bool)o) ? "this is true" : "this is false"; break;
            case "DateTime": val = "The date is: " + ((DateTime)o); break;
            case "Int32": val = "The number-value is: " + (int)o; break;
        }
        return val;
    }
    

    Hope this helps! ;)

提交回复
热议问题