开发者

Inheriting from Array class

All arrays i create in C# inherit implicitly from the Array class. So why are methods like Sort() etc not available to the array i create. For example, consider the following code:

int [] arr = new int[]{1,2,3,4,5};

Console.开发者_Go百科WriteLine(arr.Length); //This works,Length property inherited from Array

Array.Sort(arr); //Works

arr.Sort(); //Incorrect !

Please Help Thank You.


It's because the Sort method is a static method defined on the Array class so you need to call it like this:

Array.Sort(yourArray);

You don't need an instance of the class to call a static method. You directly call it on the class name. In OOP there's no notion of inheritance for static methods.


Sort is a static method on the Array class, that's why you call it using Array.Sort(). When you try arr.Sort(), you're trying to access an instance method which doesn't exist.


You could probably use an extension method to add a Sort function as an instance member of the Array type.

public static class ArrayExtension
{
    public static void Sort(this Array array)
    {
        Array.Sort(array);
    }
}

Example

int [] arr = new int[]{1,2,3,4,5};
arr.Sort();

DISCLAIMER: I have not compiled and tried this, but I am pretty sure that it will work.


Array.Sort() is a static method so you won't see it hanging off instances. However, you can use the OrderBy() extension method on any IEnumerable to do what you are seeking.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜