C# 在运行时打开对象类型

标签 c# .net

我有一个 List<object> .我想遍历列表并以比 o.ToString() 更友好的方式打印出值如果某些对象是 bool 值或日期时间等。

你会如何构建一个我可以调用的函数,比如 MyToString(o)并针对其实际类型返回格式正确(由我指定)的字符串?

最佳答案

您可以使用 dynamic keyword对于 .NET 4.0,因为您正在处理内置类型。否则,您将为此使用多态性。

例子:

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

关于C# 在运行时打开对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7149788/

相关文章:

c# - 如何在 C# 中使用 SharpSVN 库设置 SVN 提交的作者

c# - 使用异步 Controller 的强类型 RedirectToAction( future )

.net - 是否可以用 "weak"引用替换对强名称程序集的引用?

c# - 我怎么 mock 这个?

.net - WinForms : Implementation question for having my UI run independently of my BLL layer?

c# - CorfFlags 警告 CF011 关于强名称甚至在/force 之后签名

c# - 带有嵌入式 MonthCalendar 问题的 UserControl

c# - 将数据库项与 List<string> 输入进行比较

c# - C#中字符串中字符的左侧

c# - NAUDIO多输入,单输出