Why are Array.Sort() and Array.IndexOf() methods static?

坚强是说给别人听的谎言 提交于 2019-12-30 09:32:53

问题


Always was interested why are Array.Sort() and Array.IndexOf() methods made static and similar ArrayList.Sort() and ArrayList.IndexOf() are designed as member methods. Thank you for any ideas.


回答1:


In my view Array class is basically a class representation of the fixed size arrays that we declare using [] in program (you can draw the analogy like int has it's class (structure) representation as System.Int32).

Also Array class does not contain the actually array data in any instance variables but it provides just static utility functions which can be utilized to do sorting and searching in the declared fixed size arrays.

On the other hand, ArrayList is a collection class, which provides dynamic size array implementation and it has it's own data-structure to contain the data. Therefore the said methods are instance methods, so that they can work on the that particular instance's data.




回答2:


A collection class like ArrayList encapsules some kind of internal storage (presumably an array which is resized as needed, but it could also be a linked list or some other implementation). Metods like IndexOf and Sort needs access to the underlying private storage to be efficient, so they have to be instace methods.

An Array on the other hand is not encapsulated, there is public access directly to the storage. The Array.IndexOf and Array.Sort methods does not need any special access to the array data, so they might as well be static metods.



来源:https://stackoverflow.com/questions/177259/why-are-array-sort-and-array-indexof-methods-static

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!