开发者

IEnumerable when I get a real reference on the objects?

IEnumerable<T> collection;

void MyMethod(T toSearch)
{
  foreach (T t in collection)
    if (t == toSearch) {}
}

The if clause is never true.. is it because the Enumerator creates all the items instances on demand, so everytime a new Reference ?

Edited:

Another question. What happens if I one of those collection elements return in T MyMethod() . Do I have a reference on an existing instance that really resides in m开发者_StackOverflow社区emory so that all changes made on it will be reflected in that item.. or the returned element is a new instance.. or I cannot do that .. I don't understand


Assuming T is a reference type, this will be comparing the exact references - if you pass in a reference which is in the collection, it should match with no problem. It would be extremely odd for the iterator to create clones - although not impossible, of course.

However, it won't use whatever overload of == might be valid for your particular T. For example:

List<string> strings = new List<string> { "hi" };
string hi = "hi";
string otherHi = new string(new char[]{'h', 'i'});

MyMethod(hi); // Will match
MyMethod(otherHi); // Won't match

To use normal equality instead of reference equality, you might want to change your method to say:

if (EqualityComparer<T>.Default.Equals(t, toSearch))
{
    //
}


The answer is that 'it depends', but enumerators are normally used to go through (enumerate) existing objects.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜