国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#編程中使用ref和out關鍵字來傳遞數組對象的用法

2020-01-24 01:18:53
字體:
來源:轉載
供稿:網友

在 C# 中,數組實際上是對象,而不只是像 C 和 C++ 中那樣的可尋址連續內存區域。 Array 是所有數組類型的抽象基類型。 可以使用 Array 具有的屬性以及其他類成員。 這種用法的一個示例是使用 Length 屬性來獲取數組的長度。 下面的代碼將 numbers 數組的長度(為 5)賦給名為 lengthOfNumbers 的變量:

int[] numbers = { 1, 2, 3, 4, 5 };int lengthOfNumbers = numbers.Length;

Array 類提供了許多其他有用的方法和屬性,用于排序、搜索和復制數組。
示例
此示例使用 Rank 屬性來顯示數組的維數。

class TestArraysClass{  static void Main()  {    // Declare and initialize an array:    int[,] theArray = new int[5, 10];    System.Console.WriteLine("The array has {0} dimensions.", theArray.Rank);  }}

輸出:

 The array has 2 dimensions.

使用 ref 和 out 傳遞數組
與所有 out 參數一樣,在使用數組類型的 out 參數前必須先為其賦值;即必須由被調用方為其賦值。例如:

static void TestMethod1(out int[] arr){  arr = new int[10];  // definite assignment of arr}

與所有 ref 參數一樣,數組類型的 ref 參數必須由調用方明確賦值。因此,不需要由被調用方明確賦值。可以將數組類型的 ref 參數更改為調用的結果。例如,可以為數組賦以 null 值,或將其初始化為另一個數組。例如:

static void TestMethod2(ref int[] arr){  arr = new int[10];  // arr initialized to a different array}

下面兩個示例演示了 out 與 ref 在將數組傳遞給方法時的用法差異。
在此示例中,在調用方(Main 方法)中聲明數組 theArray,并在 FillArray 方法中初始化此數組。然后,數組元素將返回調用方并顯示。

class TestOut{  static void FillArray(out int[] arr)  {    // Initialize the array:    arr = new int[5] { 1, 2, 3, 4, 5 };  }  static void Main()  {    int[] theArray; // Initialization is not required    // Pass the array to the callee using out:    FillArray(out theArray);    // Display the array elements:    System.Console.WriteLine("Array elements are:");    for (int i = 0; i < theArray.Length; i++)    {      System.Console.Write(theArray[i] + " ");    }    // Keep the console window open in debug mode.    System.Console.WriteLine("Press any key to exit.");    System.Console.ReadKey();  }}

輸出:

    Array elements are:    1 2 3 4 5  

    
在此示例中,在調用方(Main 方法)中初始化數組 theArray,并通過使用 ref 參數將其傳遞給 FillArray 方法。在 FillArray 方法中更新某些數組元素。然后,數組元素將返回調用方并顯示。

class TestRef{  static void FillArray(ref int[] arr)  {    // Create the array on demand:    if (arr == null)    {      arr = new int[10];    }    // Fill the array:    arr[0] = 1111;    arr[4] = 5555;  }  static void Main()  {    // Initialize the array:    int[] theArray = { 1, 2, 3, 4, 5 };    // Pass the array using ref:    FillArray(ref theArray);    // Display the updated array:    System.Console.WriteLine("Array elements are:");    for (int i = 0; i < theArray.Length; i++)    {      System.Console.Write(theArray[i] + " ");    }    // Keep the console window open in debug mode.    System.Console.WriteLine("Press any key to exit.");    System.Console.ReadKey();  }}

輸出:

    Array elements are:    1111 2 3 4 5555

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 邮箱| 怀化市| 万全县| 大姚县| 六盘水市| 松桃| 新巴尔虎右旗| 建水县| 高青县| 霍城县| 东丰县| 横峰县| 乳山市| 文安县| 大同县| 潜江市| 越西县| 东兰县| 石屏县| 丹棱县| 丹凤县| 涟水县| 秀山| 南宁市| 开鲁县| 夏津县| 马关县| 大同县| 道真| 工布江达县| 广平县| 呼伦贝尔市| 延津县| 潮州市| 增城市| 鹰潭市| 普格县| 宜君县| 彝良县| 富阳市| 老河口市|