如何OfType< T>()的工作? [英] How does OfType<T>() Work?

查看:107
本文介绍了如何OfType< T>()的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何OfType()的工作?

How does OfType() Work?

我看了这是怎么回事上,但究竟怎样的LINQ提供此链接知道如何匹配指定类型的所有对象。我知道的IQueryable< T> 链上的请求,然后评估时的GetEnumerator()被称为(右? )。

I read this link about what's going on but how exactly does the LINQ provider know how to get all objects matching the specified type. I know the IQueryable<T> "chains" up requests and then evaluates when GetEnumerator() is called (right?).

具体来说,我想知道如何框架快快行动类型的比较?我在.NET 2.0的项目,去这样的(因为2.0不支持这些类型的功能)写了一个方法:

Specifically I want to know how does the framework quickly do type comparison? I wrote a method in a .NET 2.0 project that went like this (since 2.0 doesn't support these kind of features):

    public IEnumerable<TResult> OfType<TResult>()
        where TResult : class
    {
        foreach (TItem item in this.InnerList)
        {
            TResult matchItem = item as TResult;

            if (matchItem != null)
            {
                yield return matchItem;
            }
        }
    }

这是最好的实现?

编辑:我主要关注本 OfType&LT; T&GT;()是它的快速

My main concern with this OfType<T>() is that it is fast.

推荐答案

您目前的实现 - 设计 - 不支持值类型

Your current implementation -- by design -- doesn't support value-types.

如果你想更接近于LINQ的 OfType 的方法,支持所有类型的,那么试试这个:

If you wanted something closer to LINQ's OfType method, that supports all types, then try this:

public IEnumerable<TResult> OfType<TResult>(IEnumerable source)
{
    foreach (object item in source)
    {
        if (item is TResult)
            yield return (TResult)item;
    }
}

这篇关于如何OfType&LT; T&GT;()的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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