如何使用OfType<>筛选泛型类型的所有变体 [英] How to filter to all variants of a generic type using OfType<>

查看:172
本文介绍了如何使用OfType<>筛选泛型类型的所有变体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要使​​用OfType<>来过滤 List< ISeries> 中的对象。我的问题是,有些对象是一个通用的接口类型,但它们没有自己的共同继承接口。


我有以下定义:

pre $ public interface ISeries
public interface ITraceSeries< ; T> :ISeries
public interface ITimedSeries:ISeries
//以及更多...

我的列表包含各种各样的 ISeries ,但现在我只想得到 ITraceSeries 对象,而不管它们实际上定义了泛型类型参数,如下所示:

  var filteredList = myList.OfType< ITraceSeries<>>(); //无效的论点! 

我该怎么做?

一个不利的解决方案是引入一个继承自 ISeries 的类型 ITraceSeries



  public interface ITraceSeries< T> :ITraceSeries 

然后,使用 ITraceSeries 。但是这并没有真正添加新的信息,而只是使得继承链更加复杂。

在我看来,这是一个常见的问题,但是我没有找到有用的信息SO或网页。感谢您的帮助!

解决方案

您可以使用反射来实现它:

  var filteredList = myList.Where(
x => x.GetType()
.GetInterfaces()
.Any(i => i .IsGenericType&&(i.GetGenericTypeDefinition()== typeof(ITraceSeries<>))));


I want to filter objects in a List<ISeries> using their type, using OfType<>. 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:

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:

public interface ITraceSeries<T> : ITraceSeries

Then, use ITraceSeries as filter. 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. 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<>))));

这篇关于如何使用OfType&lt;&gt;筛选泛型类型的所有变体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆