C#怎样把List of Object转换来List of T具体品种

前一周码程序的时候碰到个难题,因为设计上的牢笼,叁个措施接受的参数只好为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<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; }
    }
}

 

相关文章