3

我正在尝试制作模板类列表,将基类传递给模板。然而,这似乎是不允许的。有没有办法绕过这个限制,或者更恰当地重组我的代码?

这是一个抽象的例子:

using System;
using System.Collections.Generic;

namespace TempInherit
{
    abstract class Shape{}

    class Triangle : Shape{}
    class Square : Shape{}

    class ShapeHolder<T>{}

    class MainClass
    {
        public static void Main(string[] args)
        {
            // list of base class, add subclass - works
            List<Shape> shapes = new List<Shape>();
            shapes.Add(new Triangle());
            shapes.Add(new Square());

            // list of holders of base class, add holders of subclass - fails
            List<ShapeHolder<Shape>> shapeHolders = new List<ShapeHolder<Shape>>();
            shapeHolders.Add(new ShapeHolder<Triangle>());
            shapeHolders.Add(new ShapeHolder<Square>());
        }
    }
}

产生:

错误 CS1502:“System.Collections.Generic.List>.Add(TempInherit.ShapeHolder)”的最佳重载方法匹配有一些无效参数 (CS1502) (TempInherit)

错误 CS1503:参数#1' cannot convert TempInherit.ShapeHolder' 表达式键入 `TempInherit.ShapeHolder' (CS1503) (TempInherit)

4

1 回答 1

6

协方差问题:

您可以创建一个 interface IShapeHolder<out T>,因为接口上的泛型参数可以是协变的(但不是在类上)

类似的东西

public class Shape
    {
    }
    public class Triangle : Shape
    {
    }
    public class Square : Shape
    {
    }
    //T generic parameter is covariant (out keyword)
    public interface IShapeHolder<out T> where T : Shape
    {
    }
    public class ShapeHolder<T>  : IShapeHolder<T> where T: Shape
    { 
    }

然后,

var shapes = new List<Shape>();
shapes.Add(new Triangle());
shapes.Add(new Square());

// list of holders of base class, add holders of subclass - fails no more
var shapeHolders = new List<IShapeHolder<Shape>>();
shapeHolders.Add(new ShapeHolder<Triangle>());
shapeHolders.Add(new ShapeHolder<Square>());
于 2013-02-06T17:14:37.437 回答