前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >C#如何把List of Object转换成List of T具体类型

C#如何把List of Object转换成List of T具体类型

作者头像
跟着阿笨一起玩NET
发布2018-09-20 15:09:21
3.6K0
发布2018-09-20 15:09:21
举报

上周码程序的时候碰到个问题,因为设计上的约束,一个方法接受的参数只能为List<object>类型,然而该方法需要处理的真实数据则是确定的List<Currency>。然而C#不允许显示的直接转换类型,并且两个方向上都不可以操作。这个问题让我爆了一会儿,最后在MSDN上找到了一个OfType<T>的拓展方法可以完成这件事。

代码语言:javascript
复制
using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            List<object> currencyListOfType = new List<object>()
            {
                new Currency(){Id = Guid.NewGuid(), Name = "a"},
                new Currency(){Id = Guid.NewGuid(), Name = "b"},
                new Currency(){Id = Guid.NewGuid(), Name = "c"}
            };

            List<object> currencyListCast = new List<object>()
            {
                "a", "b", "c"
            };
            //=>OfType如果元素存在转换不了,也不会出现异常;只转换成功的元素;如果转换不了currencies则为空的List,而不是NULL
            List<Currency> currencies = currencyListOfType.OfType<Currency>().ToList();
            //=>Cast如果元素转换不了,则会失败。
            List<Currency> currencies1 = currencyListCast.Cast<Currency>().ToList();

            Console.WriteLine("currencies list:");
            foreach (var item in currencies)
            {
                Console.WriteLine(item.Id);
            }

            Console.WriteLine("currencies1 list:");
            foreach (var item in currencies1)
            {
                Console.WriteLine(item.Id);
            }

            Console.ReadLine();
        }
    }

    public class Currency
    {
        public Guid Id { get; set; }

        public string Name { get; set; }
    }
}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2015-05-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档