Joa*_*nge 8 .net c# performance ienumerable interface
将对象传递给实现特定接口的函数是否有成本,其中函数只接受该接口?喜欢:
Change (IEnumerable<T> collection)
Run Code Online (Sandbox Code Playgroud)
我通过:
List<T>
LinkedList<T>
CustomCollection<T>
Run Code Online (Sandbox Code Playgroud)
所有这些都实现了IEnumerable.但是当你将其中的任何一个传递给Change方法时,它们是否会被转换为IEnumerable,因此有一个演员阵容,但也有失去他们独特方法的问题等等?
And*_*are 14
不,从那时起就没有演员阵容List<T>
IS-A
IEnumerable<T>
.这是使用不需要强制转换的多态.
编辑:这是一个例子:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
foo(new List<int>());
}
static void foo(IEnumerable<int> list) { }
}
Run Code Online (Sandbox Code Playgroud)
IL for Main
是:
.method private hidebysig static void Main() cil managed
{
.entrypoint
.maxstack 8
L_0000: nop
L_0001: newobj instance void [mscorlib]System.Collections.Generic.List`1<int32>::.ctor()
L_0006: call void Program::foo(class [mscorlib]System.Collections.Generic.IEnumerable`1<int32>)
L_000b: nop
L_000c: ret
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的那样,没有涉及铸造.将实例List<T>
推入堆栈,然后foo
立即调用它们.
归档时间: |
|
查看次数: |
484 次 |
最近记录: |