gpt4 book ai didi

c# - 一个用于连接具有相同接口(interface)的两个不同对象列表的衬垫

转载 作者:太空宇宙 更新时间:2023-11-03 18:35:42 26 4
gpt4 key购买 nike

考虑这个简单的代码:

public interface Iinterface { }
public class Foo : Iinterface { }
public class Bar : Iinterface { }
[TestMethod()]
public void Test_Concat()
{
var bars = new List<Bar>();
var foos = new List<Foo>();
// Ok
IEnumerable<Iinterface> concats1 = bars.Cast<Iinterface>().Concat(foos.Cast<Iinterface>());
// Compilation error
IEnumerable<Iinterface> concats2 = bars.Concat(foos);
}

我想在一行中合并两个列表,并在编译时保持类型安全

例如,如果我删除类 Foo 的接口(interface),这仍然会编译,但在运行时失败:

public interface Iinterface { }
public class Foo { }
public class Bar : Iinterface { }
[TestMethod()]
public void Test_Concat()
{
var bars = new List<Bar>();
var foos = new List<Foo>();
IEnumerable<Iinterface> concats1 = bars.Cast<Iinterface>().Concat(foos.Cast<Iinterface>());
}

如果我使用 OfType<T>() ,这不会在运行时失败,但我希望它在编译时失败。我能找到的最好的方法是使用这 3 行代码:

var list = new List<Iinterface>();
list.AddRange(bars);
list.AddRange(foos);

但是对于这么简单的事情,我想找到一个单行,如果可能的话检索一个 IEnumerable<Iinterface>而不是 List<Iinterface> .
有什么办法可以实现吗?

最佳答案

你可以只写你自己的方法吗?

由于 IEnumerable 是协变的,因此您只需指定基数

var list= Combine<IInterface>(foos, bars);

private IEnumerable<T> Combine<T>(IEnumerable<T> ListA, IEnumerable<T> ListB)
{
foreach (T t in ListA)
yield return t;
foreach (T t in ListB)
yield return t;
}

虽然你也可以直接写

var list= foos.Concat<IInterface>(bars);

关于c# - 一个用于连接具有相同接口(interface)的两个不同对象列表的衬垫,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15942716/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com