CS1502和CS1503:是我的问题还是编译器的问题

本文关键字:问题 编译器 我的 CS1502 CS1503 | 更新日期: 2023-09-27 18:17:46

以下是我的代码,为简洁起见进行了编辑:

_cvList = new List<MyCollectionView<MnpsCell>>();
        void SetStuff<C, T>(Action<int?> SetKey, float y, float h=70) where C : MnpsCell
    {
        ...
        var mcv = new MyCollectionView<C>(frame, lineLayout, false);
        mcv.Delegate = new MyDelegate<C, T>(SetKey);
        mcv.DataSource = new MyDataSource2<C, T>();
        mcv.RegisterClassForCell(typeof(C), new NSString(typeof(C).Name));
        ...
        _cvList.Add(mcv);
    }

以下是我在_cvList.Add(mcv);行上得到的错误:

  • Error CS1502: The best overloaded method match for System.Collections.Generic.List<SimpleCollectionView.MyCollectionView<SimpleCollectionView.MnpsCell>>.Add(SimpleCollectionView.MyCollectionView<SimpleCollectionView.MnpsCell>) has some invalid arguments (CS1502)
  • Error CS1503: Argument #1 cannot convert SimpleCollectionView.MyCollectionView<C> expression to type SimpleCollectionView.MyCollectionView<SimpleCollectionView.MnpsCell> (CS1503)

因为C是一个mnpcell,这对我来说没有意义。我错过什么了吗?

谢谢!

CS1502和CS1503:是我的问题还是编译器的问题

这是因为MyCollectionView不是协变的。

要实现这一点,您需要定义一个带有out修饰符的接口
interface IMyCollectionView<out T>
{ ... }

然后让你的列表看起来像这样:

_cvList = new List<IMyCollectionView<MnpsCell>>();

另一种方法是创建一个非泛型接口。

Edit如D Stanley在注释中提到的,该接口的所有方法都只能返回T,不允许将T作为参数。如果遇到这个问题,您可能需要拆分接口。