在运行时的对象类型C#开关 [英] C# Switch on Object Type at Runtime

查看:232
本文介绍了在运行时的对象类型C#开关的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名单,其中,对象> 。我想遍历列表,并打印出的值以一种更友好的方式不仅仅是 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

这篇关于在运行时的对象类型C#开关的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆