簡體   English   中英

類型參數繼承的通用類型轉換

[英]Generic Type conversion on type parameter inheritance

給出以下代碼:

namespace sample
{
    class a { }

    class b : a { }

    public class wrapper<T> { }

    class test
    {
        void test1()
        {
            wrapper<a> y = new wrapper<b>();
            //Error 11  Cannot implicitly convert type 'sample.wrapper<sample.b>' to 'sample.wrapper<sample.a>' 
        }
    }
}

從邏輯上講,由於ba ,所以wrapper<b>wrapper<a> 那為什么不能進行這種轉換,或者我怎么進行呢?

謝謝。

因為b是a,所以wrapper<b>wrapper<a>

嗯,.NET泛型類並非如此,它們不能是協變的。 您可以使用接口協方差實現類似的操作:

class a { }
class b : a { }

public interface Iwrapper<out T> { }
public class wrapper<T> : Iwrapper<T> {}

class test
{
    void test1()
    {
        Iwrapper<a> y = new wrapper<b>();
    }
}

這是協方差問題。

ba ,但是wrapper<b>不是wrapper<a>

您可以使用C#4的協方差語法來允許它,如下所示:

public interface IWrapper<out T> { ... }

public class Wrapper<T> : IWrapper<T> { ... }

這將指示CLR將Wrapper<B>視為Wrapper<A>

(記錄:C#具有大寫約定;類名使用Pascal大小寫)。

讓我們做一個場景。 讓我們將類a Mammal ,將類稱為b Dog ,並說wrapper<T>類為List<T>

看看這段代碼會發生什么

List<Dog> dogs = new List<Dog>();  //create a list of dogs
List<Mammal> mammals = dogs;   //reference it as a list of mammals

Cat tabby = new Cat();
mammals.Add(tabby)   // adds a cat to a list of dogs (!!?!)

Dog woofer = dogs.First(); //returns our tabby
woofer.Bark();  // and now we have a cat that speaks foreign languages

(我對“ 如何在字典中存儲基層孩子的答案”的部分措辭)

暫無
暫無

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

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