我正在尝试制作一个模板类列表,将基类传递给模板。然而,似乎这是不允许的。有没有办法规避这个限制,或者重新组织我的代码更加合适?
这里是一个抽象的例子:
这段文字的意思是:
错误 CS1502:最佳重载方法匹配 `System.Collections.Generic.List>。Add(TempInherit.ShapeHolder)'存在一些无效参数(CS1502)(TempInherit)
错误 CS1503:参数#1'无法将` TempInherit.ShapeHolder '表达式转换为类型` TempInherit.ShapeHolder'(CS1503)(TempInherit)
这里是一个抽象的例子:
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'无法将` TempInherit.ShapeHolder '表达式转换为类型` TempInherit.ShapeHolder'(CS1503)(TempInherit)