gpt4 book ai didi

c# - 如何将 List 转换为 List

转载 作者:IT王子 更新时间:2023-10-29 04:03:06 24 4
gpt4 key购买 nike

我有一个接口(interface)定义为:

public interface MyInterface {
object foo { get; set; };
}

和一个实现该接口(interface)的类:

public class MyClass : MyInterface {
object foo { get; set; }
}

然后我创建一个返回 ICollection 的函数,如下所示:

public ICollection<MyClass> Classes() {
List<MyClass> value;

List<MyInterface> list = new List<MyInterface>(
new MyInterface[] {
new MyClass {
ID = 1
},
new MyClass {
ID = 1
},
new MyClass {
ID = 1
}
});

value = new List<MyClass>((IEnumerable<MyClass>) list);

return value;
}

它会编译但是会抛出一个

Unable to cast object of type 'System.Collections.Generic.List1[MyInterface]'
to type
'System.Collections.Generic.IEnumerable
1[MyClass]'.

异常。我做错了什么?

最佳答案

A List<MyInterface>无法转换为 List<MyClass>一般来说,因为第一个列表可能包含实现 MyInterface 的对象但它们实际上不是 MyClass 类型的对象.

但是,由于在您的情况下您知道如何构建列表并且可以确定它只包含 MyClass对象,您可以使用 Linq 执行此操作:

return list.ConvertAll(o => (MyClass)o);

关于c# - 如何将 List<interface> 转换为 List<concrete>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6019765/

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