gpt4 book ai didi

c# - 通用模板错误

转载 作者:行者123 更新时间:2023-11-30 14:34:02 25 4
gpt4 key购买 nike

我试图制作一个模板类列表,将基类传递给模板。然而,这似乎是不允许的。有没有办法规避此限制,或更适本地重构我的代码?

这是一个抽象的例子:

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

产生:

Error CS1502: The best overloaded method match for `System.Collections.Generic.List>.Add(TempInherit.ShapeHolder)' has some invalid arguments (CS1502) (TempInherit)

Error CS1503: Argument #1' cannot convert
TempInherit.ShapeHolder' expression to type `TempInherit.ShapeHolder' (CS1503) (TempInherit)

最佳答案

协方差问题:

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

类似的东西

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>());

关于c# - 通用模板错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14734791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com