簡體   English   中英

C#通用列表合並

[英]c# generic list 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);
        }
    }
}

我將假設您沒有使用C#4.0。

在早期版本的C#,這是行不通的,因為語言不支持泛型類型的逆變協方差

不用擔心學術術語-它們只是允許的變異(即變異)種類的術語。

這是一篇關於細節的好文章: http : //blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx

為了使您的代碼正常工作,請編寫以下代碼:

list1.AddRange(list2.Cast<MyType>());

如果您使用的是C#4(.NET 4),則只需在最后一行中刪除演員表:

list1.AddRange(list2);

如果使用的是C#3(.NET 3.5),則需要使用Cast()LINQ擴展:

list1.AddRange(list2.Cast<MyType>());

您不能將list2強制轉換為List的原因是List不是協變的。 您可以在這里找到為什么不是這種情況的很好的解釋:

在C#中,為什么不能將List <string>對象存儲在List <object>變量中

第一行起作用的原因是AddRange()采用IEnumerable,而IEnumerable是協變的。 .NET 3.5沒有實現通用集合的協方差,因此在C#3中需要Cast()。

如果可以的話,也許嘗試使用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>());

您不能這樣做,因為MyType2是MyType,但是List<MyType2>不是List<MyType> 2個List<XXX>類型之間沒有繼承關系。

您可以使用LINQ的Cast方法輕松實現復制,該方法會將每個元素轉換為所需的類型。

    list1.AddRange(list2.Cast<MyType>());

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM