泛型兼容性我做错了什么

本文关键字:错了 什么 兼容性 泛型 | 更新日期: 2023-09-27 18:13:47

给出下面的代码,当我创建一个字典Dictionary<System.Type, ICrud<IShape>>时,我不能像这样添加字典。不编译Add(typeof(FourSideShape), new dataservice_FourSideShape<FourSideShape>())

我做错了什么?

 public interface ICrud<in T> where T: IShape
    {
        void save(T form);
    }
public class dataservice_Shape<T>  where T : IShape
{
    public void save(T form) {
    }
}

public class dataservice_FourSideShape<T> : ICrud<T> where T : FourSideShape 
{
    public void save(T form)
    {
    }
}
public interface IShape {
    string ShapeName {get;}
}
public abstract class Shape : IShape
{
    public abstract string ShapeName { get; }
}
public class FourSideShape : Shape
{
    public override string ShapeName
    {
        get
        {
            return "FourSided";
        }
    }
}
   Dictionary<System.Type, ICrud<IShape>> services = new Dictionary<System.Type, ICrud<IShape>>();
   // fill the map
   this.services.Add(typeof(FourSideShape), new dataservice_FourSideShape());

泛型兼容性我做错了什么

TICrud必须是协变的(将in更改为out),以便someA<someB>可以浇注到ISomeA<ISomeB>

然而,这意味着你不能有一个方法以T作为参数,只返回T -(你的保存方法无效)。

这里有一个为什么你不能做你想做的事情的例子:

void Main()
{
    var c = new Crud<Shape>(); //Crud contains a List<Shape>
    c.Save(new Shape());       //Crud.SavedItems is a List<Shape> with one item
    ICrud<IShape> broken = ((ICrud<IShape>)c);
    broken.Save(new AnotherShape()); // Invalid ! 
                                     // Trying to add a 'AnotherShape' to a List<Shape>
}
public interface IShape {
    string ShapeName {get;}
}
public interface ICrud<in T> where T: IShape
{
   void save(T form);
}
public class Shape : IShape {
    public string ShapeName { get; set; }
}
public class AnotherShape : IShape {
    public string ShapeName { get; set; }
}
public class Crud<T> : ICrud<T> where T : IShape
{
    public List<T> SavedItems  = new List<T>();
    public void save(T form)
    {
        //Do some saving..
        SavedItems.Add(form);
    }
}

你必须重新构建你的代码。也许将void save(T form);更改为void save(IShape form);并删除模板?