C# Switch on Object Type at Runtime

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

    Here's a working example with comments. It uses a generic Dictionary of Type and Lambda Func.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    
    namespace ConsoleApplication1
    {
        class Program
        {
            // a custom class
            public class MyPerson
            {
                public string FN { get; set; }
                public string LN { get; set; }
            }
            static void Main(string[] args)
            {
                // your prebuilt dictionary of Types to Lambda expressions to get a string
                Dictionary> MyToStringLookup = new Dictionary>()
                {
    
                    {typeof(String), new Func( obj => obj.ToString() )},
                    {typeof(DateTime), new Func( obj => ((DateTime)obj).ToString("d") )},
                    {typeof(MyPerson), new Func( obj => (obj as MyPerson).LN )},
                };
                // your list of objects
                List MyObjects = new List()
                {
                    "abc123",
                    DateTime.Now,
                    new MyPerson(){ FN = "Bob", LN = "Smith"}
                };
                // how you traverse the list of objects and run the custom ToString
                foreach (var obj in MyObjects)
                    if (MyToStringLookup.ContainsKey(obj.GetType()))
                        System.Console.WriteLine(MyToStringLookup[obj.GetType()](obj));
                    else // default if the object doesnt exist in your dictionary
                        System.Console.WriteLine(obj.ToString());
            }
        }
    }
    
        

    提交回复
    热议问题