Cannot implicitly convert List to Collection

后端 未结 7 2096
悲哀的现实
悲哀的现实 2020-12-08 13:44

This is a compiler error (slightly changed for readability).

This one always puzzled me. FxCop tells that this is a bad thing to return List and classes that are\\de

7条回答
  •  时光说笑
    2020-12-08 14:11

    List doesn't derive from Collection - it does, however, implement ICollection. That would be a better choice of return type.

    As for the new List(some collection) question - it partly depends on what the collection is. If it implements ICollection (at execution time) then the constructor can use its Count property to create the list with the right initial capacity before iterating through it and adding each item. If it doesn't implement ICollection then it's just equivalent to:

    List list = new List();
    foreach (int x in otherCollection)
    {
        list.Add(x);
    }
    

    Still nice to have in a convenient constructor, but not hugely efficient - it can't be, really.

    I don't believe the constructor does anything cunning for arrays, which it potentially could - using Array.Copy or whatever to just copy the lot in one go rather than iterating though. (Likewise if it were another List it could get at the backing array and copy that directly.)

提交回复
热议问题