为什么大多数System.Array方法都是静态的? [英] Why are most methods of System.Array static?
问题描述
我想这更多是一个框架设计问题。我最近想知道为什么System.Array中的大多数方法都是静态的。我的直觉总是使用Array实例上的IndexOf(object),而不是System.Array.IndexOf(array,object)。决定背后是否有主要原则,是否使方法静态?
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?
我发现了这个问题:
何时最好在ASP.NET中使用静态函数
但是我不满意:-/
推荐答案
最继承 System.Array
的时间是使用单个维度数组。例如:
The most time you inherit of System.Array
is using a single dimension array. like:
int[] a1 = new int[2];
当您定义 int []
时衍生自 System.Array
类型,例如@Sergey Rybalkin说。在这种情况下,方法 IndexOf
肯定会最好地实现为实例方法而不是静态方法。
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.
但是还有其他类型可以从System.Array继承,例如多维度数组。在这种情况下(多维度),方法 IndexOf
没有意义。
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.
对此进行测试:
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);
最后一个类似的消息引发了RankException消息在这里得到支持。
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.
...
关于注释决策背后是否有主要原则,是使方法静态还是使方法静态?
有,原理很简单。实例方法表示对象的动作或行为。静态方法是系统中与类相关的函数,或者在某些情况下是您要在不创建类实例的情况下调用的方法。
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.
在 System.Math
类中考虑一下,每次要调用 Sqrt
之类的方法时都需要实例数学时,情况会如何混乱还是 Pow
?
Think in System.Math
class how mess will be if you need instance math every time you want call a method like Sqrt
or Pow
?
我要给你的最后一个例子是 System.Text .RegularExpressions.Regex
类。此类具有作为实例实现的 Match
方法和作为静态实现的重载。
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.
这篇关于为什么大多数System.Array方法都是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!