在 C# 中转换 List 对象
我需要将一个 List 对象转换为另一个 List 对象,该对象是一个接口
public class THold : IHold
{..}
,这里,IHold 是接口。
我想这样做:
List<THold> hold = new List<THold>();
List<IHold> test = hold;
I need to cast a List object to another List object which is an interface
public class THold : IHold
{..}
Here, IHold is the interface.
I want to do this:
List<THold> hold = new List<THold>();
List<IHold> test = hold;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最接近的是:
问题是不存在直接转换。如果我有以下情况怎么办:
然后:
显然
UHold
实现了IHold
接口,但也显然无法添加到THold
列表中对象。The closest you're going to come is:
The problem is that a direct cast doesn't exist. What if I had the following:
And then:
Obviously
UHold
implements theIHold
interface but also obviously can't be added to the list ofTHold
objects.那么,
List<>
不能以非泛型形式创建;我猜您在撰写帖子时丢失了尖括号。不管怎样,我猜你想从
List
转到List
,反之亦然。无论哪种方式,最好的选择是 Linq 的 OfType() 方法:Cast<>()
方法也应该有效,但是我发现每当我尝试使用它来执行其规定的任务时,它永远不会工作正常。将 Select() 与投射每个项目的投影一起使用也将起作用:Well,
List<>
cannot be created in non-generic form; I'm guessing you lost the angle brackets somewhere in writing your post.Anyway, I'm guessing you want to go from a
List<THold>
to aList<IHold>
, or vice versa. Either way, the best option is the OfType() method of Linq:The
Cast<>()
method should also work, however I find whenever I try to use it to perform its stated task it never works right. Using Select() with a projection that casts each item will also work:这篇 msdn 文章介绍了协变和逆变,它们是您所要表达的术语描述。
This msdn article describes co- and contravariance which are the terms of what you describe.