博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C#如何把List of Object转换成List of T具体类型
阅读量:6967 次
发布时间:2019-06-27

本文共 1292 字,大约阅读时间需要 4 分钟。

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

using System;using System.Collections.Generic;using System.Linq;namespace ConsoleApplication1{    internal class Program    {        private static void Main(string[] args)        {            List currencyListOfType = new List()            {                new Currency(){Id = Guid.NewGuid(), Name = "a"},                new Currency(){Id = Guid.NewGuid(), Name = "b"},                new Currency(){Id = Guid.NewGuid(), Name = "c"}            };            List currencyListCast = new List()            {                "a", "b", "c"            };            //=>OfType如果元素存在转换不了,也不会出现异常;只转换成功的元素;如果转换不了currencies则为空的List,而不是NULL            List
currencies = currencyListOfType.OfType
().ToList(); //=>Cast如果元素转换不了,则会失败。 List
currencies1 = currencyListCast.Cast
().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; } }}

 

转载地址:http://ojisl.baihongyu.com/

你可能感兴趣的文章
有间距的表格布局 table布局
查看>>
Java 设计模式—装饰者模式
查看>>
实战c++中的vector系列--vector的遍历(stl算法、vector迭代器(不要在循环中推断不等于end())、operator[])...
查看>>
【一步步学OpenGL 20】 -《点光源》
查看>>
Spring -- <mvc:annotation-driven />
查看>>
java.net.ServerSocket 解析
查看>>
33-hadoop-cdh搭建coudemanager安装
查看>>
【iCore1S 双核心板_ARM】例程十四:FATFS实验——读写文件
查看>>
CPU 虚拟化
查看>>
circRNA 在人和小鼠脑组织中的表达
查看>>
新人替代旧人
查看>>
2步安装1个hive docker运行环境[centos7]
查看>>
Android Keystore 对称-非对称加密
查看>>
工作总结 获取html 标签 自定义属性值 根据html 自定义属性 获取 到标签...
查看>>
window.external的使用
查看>>
wait/waitpid函数与僵尸进程、fork 2 times
查看>>
iOS中Storyboard使用要点记录
查看>>
payload和formData有什么不同?
查看>>
【文件监控】之一:理解 ReadDirectoryChangesW part1
查看>>
Objective-C
查看>>