[英]Difference between var and IEnumerable in C#?
我读此文章,了解VAR和IEnumerable之间的差异。 作者写了如下四点
点号 我对3和4不清楚。 请通过示例帮助理解这些观点
此处的所有内容都不对,因此至少要简短一点:
var
不会改变这一点; IEnumerable
通常只是做代表内存中的集合(它不就得了,头脑,因为它是唯一的坚持,不管他们最终存储的合同集合TOI)和观念在很大程度上并列这个问题的休息; 不过,请注意使用var
来给出更广泛的概念:使用var
通常仅是在根据当前语句得出的结果类型明显时才是一个好主意-我真的不理解Darren的推理或如何很有用,但请考虑以下因素:
var results0 = new List<string>(); // assignment type is obvious
var results1 = something.GetResult(); // read must investigate to know
var
是上下文关键字,它隐式地键入变量。 当您使用IEnumerable<T>
您将明确说明要定义的类型,因为var将使用类型推断。
使用哪一种并没有真正的区别,更多的是使用IMO的编码样式,当我使用LINQ
而不是IEnumerable<T>
或IQueryable<T>
从集合中返回内容时,我个人使用var
。
var value5 = list.Where(i => i == 5).ToList();
IEnumerable<int> value5 = list.Where(i => i == 5).ToList();
两者将产生相同的输出。
关于第3点和第4点,我认为IEnumerable对内存收集根本没有任何好处。 在后台, CLR
将在运行时推断变量类型(使用var时),最有可能是IEnumerable<T>
。
var
只是一个隐式类型的局部变量。 您只需让编译器确定类型。
var i = 10; // Implicitly typed
int j = 10; // Explicitly typed
当使用匿名类型时,例如,它也非常方便。
var anon = new { Foo = "Bar" };
Console.WriteLine(anon.Foo); // Puts "Bar" on console.
如果有人说var MyList = SomeStringCollection.ToList()
; MyEnumerator = MyList.GetEnumerator(); , then the type of
MyList , and the type of
will be
List , and the type of
MyEnumerator , and the type of
will be
List.Enumerator , which is a *value type* that implements
IEnumerator的“ , which is a *value type* that implements
, and will thus exhibit *value semantics*. If the type of
, and will thus exhibit *value semantics*. If the type of
MyList的, the return type of
had been
IEnumerable , the return type of
MyList.GetEnumerator() , the return type of
would have been
IEnumerator`,它具有参考语义 。
如果例如一个方法具有从IEnumerator<String>
读取五个项的方法,则这种区别可能很重要。 如果使用变量IEnumerator<String>
多次调用这样的方法,则每次调用都会从枚举中读取下五个项目。 相比之下,如果使用值类型如List<String>.Enumerator
多次调用这种方法,则每次调用会将枚举状态复制到实现IEnumerator<T>
的新堆对象中,然后将该对象传递给方法(将读取其中的五个项目),然后放弃该对象及其关联的空间(不影响与原始变量关联的枚举状态)。
请注意,在大约99%的情况下,值语义或引用语义在枚举器中同样可以接受; 在大多数情况下,值语义将使代码运行速度更快,而很少使代码运行速度显着降低。 此外,在某些情况下,知道枚举器将充当值类型可能会在语义上有用(例如,如果希望能够重复重新枚举集合的一部分)。 另一方面,对于使用IEnumerator<T>
实现的代码来了解它们可能使用的实现类型,这可能是一个好主意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.