Why are most methods of System.Array static? [closed]

ぐ巨炮叔叔 提交于 2020-03-15 17:56:38

问题


I guess this is more of a framework design question. I recently wondered why most of the methods in System.Array are static. My gut reaction always is to use e.g. IndexOf(object) on the Array instance, not as System.Array.IndexOf(array, object). Is there a main principle behind the decision, whether to make a method static or not?

I found this question: When is it best to use Static Functions in ASP.NET

But it didn't satisfy me :-/


回答1:


The most time you inherit of System.Array is using a single dimension array. like:

int[] a1 = new int[2];

When you define int[] this implicitly derived from System.Array type like @Sergey Rybalkin says. In this case the method IndexOf would surely be best implemented as a instance method and not as static method.

But there is another types that inherit from System.Array like mult dimension arrays. In this case (mult dimension) the method IndexOf does not make sense.

Test this:

int[,] arr = new int[2, 2];

arr[0, 0] = 3; arr[1, 0] = 4;
arr[0, 1] = 5; arr[1, 1] = 6;

Array.IndexOf(arr, 4);

The last like throws a RankException with the message "Only single dimension arrays are supported here."

Perhaps, and most probably, because of that this method is implemented as static.

...

About the comment Is there a main principle behind the decision, whether to make a method static or not?

There is, and the principle is quite simple. The instance method represents a action or behavior of a object. The static method is a function of the system that is logic related with the class, or in some cases a method you want to call without creating an instance of the class.

Think in System.Math class how mess will be if you need instance math every time you want call a method like Sqrtor Pow?

The final example I will give to you is the System.Text.RegularExpressions.Regex class. This class have a Match method implemented as instance and an overload implemented as static.

Each one is used in a diferent context. The instance is used when you use the same pattern multiple times. The static when you use the pattern a unique time in your code.



来源:https://stackoverflow.com/questions/16713384/why-are-most-methods-of-system-array-static

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