在运行时的对象类型C#开关对象、类型

2023-09-02 21:39:03 作者:朝天吼i

我有一个名单,其中,对象> 。我想遍历列表,并打印出的值以一种更友好的方式不仅仅是 o.ToString()的情况下,一些对象是布尔或日期时间等

I have a List<object>. 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 the objects are booleans, or datetimes, etc.

你会如何构建一个功能,我可以打电话像 MyToString(O)并返回其实际的类型(由我指定)正确格式化字符串?

How would you structure a function that I can call like MyToString(o) and return a string formatted correctly (specified by me) for its actual type?

推荐答案

您可以使用的动态关键字这与.NET 4.0,因为你正在处理的内建类型。否则,你会使用多态这一点。

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.

例如:

using System;
using System.Collections.Generic;

class Test
{
    static void Main()
    {
        List<object> stuff = new List<object> { 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");
    }
}

打印出来:

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