为什么List.Sort()的实例方法,但的Array.Sort()静态? [英] Why is List.Sort() an instance method but Array.Sort() static?

查看:154
本文介绍了为什么List.Sort()的实例方法,但的Array.Sort()静态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解这部分的语言背后的设计决策。我承认我是很新的这一切,但,这是一些东西,抓住了我出去一开始,我在想,如果我失去了一个明显的原因。请看下面的code:

I'm trying to understand the design decision behind this part of the language. I admit i'm very new to it all but this is something which caught me out initially and I was wondering if I'm missing an obvious reason. Consider the following code:

List<int> MyList = new List<int>() { 5, 4, 3, 2, 1 };
int[] MyArray = {5,4,3,2,1};


//Sort the list
MyList.Sort();
//This was an instance method


//Sort the Array
Array.Sort(MyArray);
//This was a static method

为什么他们不能同时实现以同样的方式 - 直觉它对我来说更有意义,如果他们都是实例方法

Why are they not both implemented in the same way - intuitively to me it would make more sense if they were both instance methods?

推荐答案

这个问题很有趣,因为它揭示了.NET类型系统的细节。就像值类型,串并委托类型,数组类型得到.NET特殊待遇。最显着的oddish的行为是你从来没有明确地声明数组类型。编译器需要照顾它为您的抖动充足的发展帮助。 System.Array的是一个抽象类,你会得到专用数组类型以书面code的过程。无论是通过显式地创建一个类型[]或通过使用通用类在其​​基实现的数组。

The question is interesting because it reveals details of the .NET type system. Like value types, string and delegate types, array types get special treatment in .NET. The most notable oddish behavior is that you never explicitly declare an array type. The compiler takes care of it for you with ample helpings of the jitter. System.Array is an abstract type, you'll get dedicated array types in the process of writing code. Either by explicitly creating a type[] or by using generic classes that have an array in their base implementation.

在一个相当大的程序,有数百个数组类型是不寻常的。它是没问题的,但有间接参与为每种类型。这是需要的那种类型,而不是它的对象存储。它的最大的一块是所谓的方法表。概括地说,它是指向的类型的每个实例方法的列表。无论是类加载器和抖动一起工作来填补这个表。这通常被称为V形表,但并不完全匹配,该表包含指向了既非虚拟和虚拟方法

In a largish program, having hundreds of array types is not unusual. Which is okay, but there's overhead involved for each type. It is storage required for just the type, not the objects of it. The biggest chunk of it is the so-called 'method table'. In a nutshell, it is a list of pointers to each instance method of the type. Both the class loader and the jitter work together to fill this table. This is commonly known as the 'v-table' but isn't quite a match, the table contains pointers to methods that are both non-virtual and virtual.

您可以看到这导致也许,设计师们担心有很多类型的大法表。因此,寻找方法来减少开销。

You can see where this leads perhaps, the designers were worried about having lots of types with big method tables. So looked for ways to cut down on the overhead.

的Array.Sort()就是一个明显的目标。

Array.Sort() was an obvious target.

同样的问题是不相关的泛型类型。仿制药,很多,一种方法表可以处理方法指针引用类型中的任何类型的参数中的一个大的准确。

The same issue is not relevant for generic types. A big nicety of generics, one of many, one method table can handle the method pointers for any type parameter of a reference type.

这篇关于为什么List.Sort()的实例方法,但的Array.Sort()静态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆