c#通用列表合并

Dar*_*kas 2 c# collections merge

我无法合并列表和列表?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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Bev*_*van 5

我假设你没有使用C#4.0.

在早期版本的C#中,这不起作用,因为该语言不支持泛型类型的逆变协方差.

不要担心学术术语 - 它们只是允许的各种差异(即变化)的术语.

这是一篇关于细节的好文章:http: //blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx

要使代码有效,请写下:

list1.AddRange(list2.Cast<MyType>());
Run Code Online (Sandbox Code Playgroud)