C# 泛型列表合并

3
我该如何合并List和List?面向对象编程(OOP)说MyType2是MyType…
using System;
using System.Collections.Generic;

namespace two_list_merge
{
    public class MyType
    {
        private int _attr1 = 0;

        public MyType(int i)
        {
            Attr1 = i;
        }

        public int Attr1
        {
            get { return _attr1; }
            set { _attr1 = value; }
        }
    }

    public class MyType2 : MyType
    {
        private int _attr2 = 0;

        public MyType2(int i, int j)
            : base(i)
        {
            Attr2 = j;
        }

        public int Attr2
        {
            get { return _attr2; }
            set { _attr2 = value; }
        }
    }

    class MainClass
    {
        public static void Main(string[] args)
        {
            int count = 5;
            List<MyType> list1 = new List<MyType>();
            for(int i = 0; i < count; i++)
            {
                list1[i] = new MyType(i);
            }

            List<MyType2> list2 = new List<MyType2>();
            for(int i = 0; i < count; i++)
            {
                list1[i] = new MyType2(i, i*2);
            }           

            list1.AddRange((List<MyType>)list2);
        }
    }
}

我的问题的主要点是什么? - Darius Kucinskas
3个回答

5

3
如果您正在使用C#4(.NET 4),则可以在最后一行中简单地删除转换操作:
list1.AddRange(list2);

如果您正在使用C#3(.NET 3.5),则需要使用Cast() LINQ扩展:
list1.AddRange(list2.Cast<MyType>());

你无法将list2转换为List的原因是List不是协变的。你可以在这里找到一个很好的解释,说明为什么会这样:In C#,为什么不能将List<string>对象存储在List<object>变量中
第一行代码之所以可以工作是因为AddRange()接受IEnumerable,而IEnumerable是协变的。.NET 3.5没有实现泛型集合的协变,因此需要在C#3中使用Cast()函数。

0

如果可以的话,尝试使用LINQ,以及对MyType进行显式转换。使用C# 4。

List<MyType> list1 = new List<MyType> 
     { new MyType(1), new MyType(2), new MyType(3)};

List<MyType2> list2 = new List<MyType2> 
     { new MyType2(11,123), new MyType2(22,456), new MyType2(33, 789) };

var combined = list1.Concat(list2.AsEnumerable<MyType>());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接