C# Switch on Object Type at Runtime

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

    You can use the dynamic keyword for this with .NET 4.0, since you're dealing with built in types. Otherwise, you'd use polymorphism for this.

    Example:

    using System;
    using System.Collections.Generic;
    
    class Test
    {
        static void Main()
        {
            List stuff = new List { DateTime.Now, true, 666 };
            foreach (object o in stuff)
            {
                dynamic d = o;
                Print(d);
            }
        }
    
        private static void Print(DateTime d)
        {
            Console.WriteLine("I'm a date"); //replace with your actual implementation
        }
    
        private static void Print(bool b)
        {
            Console.WriteLine("I'm a bool");
        }
    
        private static void Print(int i)
        {
            Console.WriteLine("I'm an int");
        }
    }
    
    
    

    Prints out:

    I'm a date
    I'm a bool
    I'm an int
    

    提交回复
    热议问题