我有一个 List<object>
。我想遍历列表并以比 o.ToString()
更友好的方式打印值,以防某些对象是 bool 值或日期时间等。
您将如何构建一个我可以像 MyToString(o)
一样调用的函数并返回一个正确格式化(由我指定)的字符串的实际类型?
最佳答案
您可以在 .NET 4.0 中使用 dynamic keyword,因为您要处理内置类型。否则,您将为此使用多态性。
例子:
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/