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

问题描述 投票:1回答:1

我一直在努力解决这个问题,并研究了类似的问题,但是在这里没有得到适当的解决方案。

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

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

由于无法转换

c# .net generics covariance
1个回答
0
投票

如果您的课程应该在该IEnumerable<T>上有一个二传手,则它不能是协变的。协方差是只读的,逆方差是只写的。如果您既需要又需要此类配置的集合,则您的设计有缺陷。

如果您只希望对该属性具有get访问权限,那么您首先需要为您的类创建一个接口,因为方差仅适用于通用接口:

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进行读写的类型一起使用。

© www.soinside.com 2019 - 2024. All rights reserved.