类型参数继承的通用类型转换

时间:2012-12-11 12:48:24

标签: c#

给出以下代码:

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

从逻辑上讲,自b a以来,wrapper<b>wrapper<a>。那么为什么我不能进行这种转换,或者我该怎么做呢?

感谢。

3 个答案:

答案 0 :(得分:3)

  

由于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>();
    }
}

答案 1 :(得分:1)

这是一个协方差问题。

班级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-cased)。

答案 2 :(得分:0)

让我们做一个场景。让我们拨打课程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

(我对How to store base class children in a dictionary?的回答的解释)