类型参数继承上的泛型类型转换



给定以下代码:

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>' 
        }
    }
}

从逻辑上讲,a自bawrapper<b>wrapper<a>。那为什么我不能进行这种转换,或者我该如何进行转换?

谢谢。

由于 B 是 A,因此 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# 具有大写约定;类名是帕斯卡大小写的)。

让我们做一个场景。我们称类为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

(转述我关于如何在字典中存储基类子项的答案?

最新更新