List< T>投放算法和性能注意事项 [英] List<T> Casting algorithms and performance considerations

查看:77
本文介绍了List< T>投放算法和性能注意事项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

class Program
    {
        static void Main(string[] args)
        {
            List<A> aList = new List<A>();

            var aObj = new A();

            aObj.Go(aList.Cast<IB>());
        }
    }

    class A : IB
    {
        public void Go(IEnumerable<IB> interfaceList)
        {
            foreach (IB ibby in interfaceList)
            {
                Console.WriteLine("Here");
            }
        }
    }

    interface IB
    {
        void Go(IEnumerable<IB> interfaceList);
    }

}

我最初尝试传递一个列表,但是无效
SO 的大量帮助下,我发现传递IEnumerable是将对象作为.ofType(IB)传递的唯一方法。

I originally tried passing a List but that doesn't work. After a lot of help from SO I found that passing IEnumerable is the only way to get the objects across as .ofType(IB).

对我来说不幸的是,在我的代码中,以下行将被执行数千次:

Unfortunately for me, in my code the following line will be executed thousands of times:

aList.Cast<IB>();

我想知道是否有人知道它是如何算法实现的(在IL中),它的时间顺序是什么。

I was wondering if anyone knew how it was implemented algorithmically (in IL) and what its time order is.

就是说,它比仅投射每个项目的foreach循环要快,还是它的作用到底是什么?

That is to say, is it faster than a foreach loop that just casts each item, or is that exactly what it does?

编辑主类需要维护实际对象的列表。但是只允许读者通过界面触摸它们。

EDIT The main class needs to maintain a list of the actual objects. But the reader is only allowed to touch them through the interface.

推荐答案

您应将 Go 更改为:

public void Go<T>(IEnumerable<T> interfaceList)
    where T : IB
{
    foreach (IB ibby in interfaceList)
    {
        Console.WriteLine("Here");
    }
}

那么您就可以了,不需要打电话发布。我怀疑Cast的源代码实现非常简单,尽管我认为它在3.5和3.5SP1之间发生了变化。但是,可能需要以常规迭代器块的方式设置新的状态机等。最好避免使用它。

Then you'll be fine with no need to call Cast. I suspect the source code implementation of Cast is pretty simple, although I believe it changed between 3.5 and 3.5SP1. However, it probably needs to set up a new state machine etc in the normal iterator block fashion. Better to avoid it if possible.

即使新方法是通用的,类型推断通常也应该为您解决,因此您无需指定 T 明确。

Even though the new method is generic, type inference should usually take care of it for you so you don't need to specify T explicitly.

这篇关于List&lt; T&gt;投放算法和性能注意事项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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