c# - 如何通过泛型使用嵌套类列表创建基类列表而不进行强制转换

标签 c# .net generics collections

我想为 ICollection<T2> 提供一个扩展方法女巫回到我身边IReadOnlyCollection<T1> .我需要所有这些,以免在代码中重复自己。我有以下代码:

public static IReadOnlyCollection<T1> All<T1, T2>(this ICollection<T2> storage) where T1 : T2
{
    if (storage.Count > 0)
    {
        return new List<T1>(storage);
    }
    else
    {
        return new List<T1>();
    }
}

但遗憾的是它无法编译。 那么让我们看一个更简单的上面的例子:

public interface IDatabase {}
public class Database : IDatabase, IDisposable {}

public static IReadOnlyCollection<T1> All<T1, T2>(this ICollection<T2> storage) where T2 : T1 where T1 : new()
{
    // compiles
    List<Database> derivedList = new List<PublishedDatabase>();
    List<IDatabase> baseList = new List<IPublishedDatabase>(derivedList);

    // doesn't compile
    // with casting it works
    List<T2> derivedListT = new List<T2>();
    List<T1> baseList1T = new List<T1>(derivedListT/* as IEnumerable<T1>*/);

    //...
}

我可以通过泛型使用嵌套类列表创建基类列表而不进行强制转换吗?

最佳答案

我可能误解了这里的约束条件,但您可以暂时使用 dynamic欺骗分析器

public static IReadOnlyCollection<T1> All<T1, T2>(this ICollection<T2> storage) where T2: T1
{
    dynamic temp = storage;
    return new ReadOnlyCollection<T1>(new List<T1>(temp));
}

...

var list = new List<SomeChild>()
               {
                  new SomeChild()
               };

var interfaces = list.All<ISomeBase, SomeChild>();

注意:如果您的代码分析器提示强制转换,您会认为他们会更加提示dynamic...也完全未经测试,可能有更好的方法来做到这一点

关于c# - 如何通过泛型使用嵌套类列表创建基类列表而不进行强制转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55335911/

相关文章:

c# - 无法解析 XmlDictionaryWriter?

c# - App.config 中的 Winforms 连接字符串

c# - 如何通过 XAML 为 Enum 类型的子项设置 MenuItem 的 IsChecked 属性?

Java 泛型类型和对象类

c# - 无法启动多个进程 (C#)

c# - 在 GridView 中使用自动生成的列提取列数和标题文本

.net - 基于DependencyKey清理缓存

.net - swagger .net core API 操作错误的不明确 HTTP 方法

c# - 在泛型方法中比较结构

java - 具体类的GenericType