简体   繁体   English

将接口列表转换为实现列表,反之亦然

[英]Cast interface list to implementation list or vice-versa

I am just not getting how to convert or cast List<ISomeImplementation> to List<SomeImplementation> . 我只是不知道如何将List<ISomeImplementation>转换或转换为List<SomeImplementation>

// lstOfImplemantation is of type `List<SomeImplementation>`
    List<ISomeImplementation> lstOfInterfaces = lstOfImplemantation; // how to convert it.

any help is appreciated. 任何帮助表示赞赏。

You can use LINQ in one way: 您可以通过一种方式使用LINQ:

List<ISomeImplementation> lstOfInterfaces = lstOfImplemantation.Cast<IISomeImplementation>().ToList();

Casting interface to implementation is not good pratice. 实现的强制转换接口不是很好的做法。 What if there some other implementations of that interface? 如果该接口还有其他实现,该怎么办? You cannot assume that all implemtations are the of type SomeImplementation . 您不能假定所有实现都是SomeImplementation类型的。 If you are sure, use List<SomeImplementation> . 如果确定,请使用List<SomeImplementation>

Just because A derives from B , doesn't necessarily mean X<A> derives from X<B> . 仅仅因为A衍生自B ,并不一定意味着X<A>衍生自X<B>

In fact, List<T> is invariant in its generic type paramater T . 实际上, List<T>在其通用类型参数T不变的 This means List<string> isn't a subtype nor a supertype of List<object> , even though string derives from object . 这意味着即使string来自objectList<string>也不是List<object>的子类型或超类型。

Imagine if your list of interfaces contained instances of type SomeOtherImplementation . 想象一下,如果您的接口列表包含类型SomeOtherImplementation实例。 How would the cast work? 演员阵容将如何运作?

Instead, you should create a new list and cast each item in your list of interfaces to the concrete type. 相反,您应该创建一个列表,并将接口列表中的每个项目强制转换为具体类型。

List<SomeImplementation> lstOfImplementation =
             lstOfInterfaces.Cast<SomeImplementation>()
                            .ToList();

If you're not sure whether all instances are of type SomeImplementation , you can filter out those who aren't, using OfType<T> . 如果不确定所有实例的类型是否为SomeImplementation ,则可以使用OfType<T>过滤掉那些实例。

List<SomeImplementation> lstOfImplementation =
             lstOfInterfaces.OfType<SomeImplementation>()
                            .ToList();

Read also: 另请阅读:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM