包含多个通用对象的列表(协方差问题)

List with Multiple Generic Objects (Covariance Issue)

我一直在努力解决这个问题,并查看了类似的问题,但在这里没有找到合适的解决方案。

我正在使用通用 class 来保存导出配置

public class SpreadsheetConfiguration<T> where T : class 
{
    public IEnumerable<T> ExportData {get; set;}
    // More stuff here
}

我有一种情况需要这些列表,它们可能不是同一类型,例如像这样

public byte[] ExportMultipleSheets(IEnumerable<SpreadsheetConfiguration<object>> toExport)

但我终究无法弄清楚如何进行这项工作,我已经查看了上面关于制作 ISpreadsehetConfiguration 或其他方面的其他路线。

这是一个开源项目:https://github.com/IowaComputerGurus/netcore.utilities.spreadsheet

我知道我遗漏了一些东西,但我已经尝试了以上所有方法,但仍然没有达到我仍然可以做的最终用法

var toExport = new SpreadsheetConfiguration<MyOtherClass>();

因为转换失败

如果你的 class 应该在那个 IEnumerable<T> 上有一个 setter 那么它就不能是协变的。协变是只读的,逆变是只写的。如果您同时需要并且还需要这些配置的集合,那么您的设计就有缺陷。

如果您只愿意 get 访问 属性,那么您首先需要为 class 创建一个接口,因为变体仅适用于通用接口:

public interface ISpreadsheetConfiguration<out T> where T : class
{
    IEnumerable<T> ExportData { get; }
}

public class SpreadsheetConfiguration<T> : ISpreadsheetConfiguration<T> where T : class
{
    public IEnumerable<T> ExportData {get; set;}
}

注意接口类型参数声明中的 out 关键字——这意味着 ISpreadsheetConfiguration<T>T 中是协变的。

现在您可以这样做了:

public byte[] ExportMultipleSheets(IEnumerable<ISpreadsheetConfiguration<object>> toExport);


var toExport = new ISpreadsheetConfiguration<object>[]
{
    new SpreadsheetConfiguration<MyOtherClass>(),
    new SpreadsheetConfiguration<CompletelyDifferentClass>()
};

ExportMultipleSheets(toExport);

有关方差的更多信息以及为什么协方差不能用于允许读取和写入类型 T here.

的类型