简体   繁体   English

如何使用OfType <>过滤到泛型类型的所有变体

[英]How to filter to all variants of a generic type using OfType<>

I want to filter objects in a List<ISeries> using their type, using OfType<>. 我想使用List<ISeries>使用它们的类型过滤List<ISeries>对象。 My problem is, that some objects are of a generic interface type, but they do not have a common inherited interface of their own. 我的问题是,某些对象属于通用接口类型,但它们没有自己的公共继承接口。

I have the following definitions: 我有以下定义:

public interface ISeries
public interface ITraceSeries<T> : ISeries
public interface ITimedSeries : ISeries
//and some more...

My list contains all kinds of ISeries , but now I want to get only the ITraceSeries objects, regardless of their actually defined generic type parameter, like so: 我的列表包含各种ISeries ,但现在我想只获取ITraceSeries对象,而不管它们实际定义的泛型类型参数如何,如下所示:

var filteredList = myList.OfType<ITraceSeries<?>>(); //invalid argument!

How can I do that? 我怎样才能做到这一点?

An unfavored solution would be to introduce a type ITraceSeries that inherits from ISeries : 一个不好使的解决办法是引入一个类型ITraceSeries从继承ISeries

public interface ITraceSeries<T> : ITraceSeries

Then, use ITraceSeries as filter. 然后,使用ITraceSeries作为过滤器。 But this does not really add new information, but only make the inheritance chain more complicated. 但这并没有真正添加新信息,只会使继承链更复杂。

It seems to me like a common problem, but I did not find useful information on SO or the web. 在我看来,这似乎是一个常见问题,但我没有在SO或网络上找到有用的信息。 Thanks for help! 感谢帮助!

You can use reflection to achieve it: 您可以使用反射来实现它:

var filteredList = myList.Where(
    x => x.GetType()
          .GetInterfaces()
          .Any(i => i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(ITraceSeries<>))));
from s in series
where s.GetType().GetGenericTypeDefinition()==typeof(ITraceSeries<>)
select s;

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

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