This开发者_开发百科 could even be a simple question even a school boy can answer.
What is the similarities and differences between "ForEach" and "Using" (asked in an interview).
My assumption was
1)Both are enumerable
2) Using can handle memory resources,but foreach can't.using supports IDisposable,foreach can't.
I wish to know the answers.
- Nope
- Nope,
foreach
will dispose of yourIEnumerable
if it implementsIDisposable
.
using
defines a scope, outside of which an object or objects will be disposed. It does not loop or iterate.
They both serve very different purposes.
foreach
is made for enumerating items in a collection/array. using
is a handy construction for making sure that you properly dispose of the thing your using. Even when exceptions are thrown for example.
Similarities for these two constructs are just, weird. Can anyone think of any similarities (apart from the very obvious: 'they are both keywords in C#')?
Similarities:
- they are both logical code expansions, providing boiler-plate code of otherwise complex scenarios
- both involve a hidden variable introduced by the compiler: for the iterator and the snapshot of the disposable object, respectively
But that is about where it ends...
using
demandsIDisposable
;foreach
might trigger fromIEnumerable[<T>]
, but is actually duck typed (you don't needIEnumerable
forforeach
)using
has a predictabletry
/finally
construct;foreach
might involve aDispose()
if the iterator isIEnumerable<T>
If anything, I'd say using
is closer to lock
than to foreach
.
The main difference between foreach
and using
is that foreach
is used for enumerating over an IEnumerable
whereas a using
is used for defining a scope outside of which an object will be disposed.
There is one similarity between foreach
and using
: Enumerators implement IDisposable
and a foreach
will implicitly wrap the use of an enumerator in a using
block. Another way of saying this is that is that a foreach
can be recoded as a using block and the resulting IL will be identical.
The code block
var list = new List<int>() {1, 2, 3, 4, 5};
foreach(var i in list) {
Console.WriteLine(i);
}
is effectively the same as
var list = new List<int>() {1, 2, 3, 4, 5};
using (var enumerator = list.GetEnumerator()) {
while (enumerator.MoveNext()) {
Console.WriteLine(enumerator.Current);
}
}
精彩评论