C#中的Array.GetValue()方法用於獲取當前Array中指定元素的值。此方法的重載列表中共有8個方法,如下所示:
- Array.GetValue(Int32,Int32)
- Array.GetValue(Int64,Int64)
- Array.GetValue(Int32)
- Array.GetValue(Int64)
- Array.GetValue(Int32,Int32,Int32)
- Array.GetValue(Int64,Int64,Int64)
- GetValue(Int32 [])
- GetValue(Int64 [])
在這裏,我們解釋Array.GetValue(Int32)和Array.GetValue(Int64)方法。
GetValue(Int32)方法用於獲取一維Array中指定位置的值。索引被指定為32位整數。
用法:
public object GetValue (int index);
在這裏,索引是32位整數,代表要獲取的Array元素的位置。
返回值:此方法返回對象類型的一維數組中指定位置的值。
異常:
- ArgumentException:如果當前數組不完全具有一維。
- IndexOutOfRangeException:如果索引超出當前數組的有效索引範圍。
GetValue(Int64)方法用於獲取一維數組中指定位置的值。索引被指定為64位整數。
用法:
public object GetValue (long index);
在這裏,索引是代表要獲取的Array元素位置的64位整數。
返回值:此方法返回對象類型的一維數組中指定位置的值。
異常:
- ArgumentException:如果當前數組不完全具有一維。
- IndexOutOfRangeException:如果索引超出當前數組的有效索引範圍。
範例1:
// C# program to demonstrate the
// Array.GetValue(Int32) Method
using System;
public class GFG {
public static void Main()
{
// declare a character array
char[] arr = new char[]{'A', 'B', 'C', 'D'};
// use of GetValue(Int32) Method
Console.WriteLine("element at index 3 is:" + arr.GetValue(3));
Console.WriteLine("element at index 1 is:" + arr.GetValue(1));
Console.WriteLine("element at index 2 is:" + arr.GetValue(2));
Console.WriteLine("element at index 0 is:" + arr.GetValue(0));
}
}
輸出:
element at index 3 is:D element at index 1 is:B element at index 2 is:C element at index 0 is:A
範例2:
// C# program to demonstrate the
// Array.GetValue(Int64) Method
using System;
public class GFG {
public static void Main()
{
// declare a string array
string[] arr = new string[5];
// use "SetValue()" method to set
// the value at specified index
arr.SetValue( "C++", 0 );
arr.SetValue( "Java", 1 );
arr.SetValue( "C#", 2 );
arr.SetValue( "Perl", 3 );
arr.SetValue( "Python", 4 );
// Using GetValue(Int32) Method
Console.WriteLine("element at index 3 is:" + arr.GetValue(3));
Console.WriteLine("element at index 1 is:" + arr.GetValue(1));
Console.WriteLine("element at index 2 is:" + arr.GetValue(2));
Console.WriteLine("element at index 0 is:" + arr.GetValue(0));
Console.WriteLine("element at index 0 is:" + arr.GetValue(4));
}
}
輸出:
element at index 3 is:Perl element at index 1 is:Java element at index 2 is:C# element at index 0 is:C++ element at index 0 is:Python
注意:對於在線編譯器,不能使用32位或64位整數。將脫機編譯器用於32或64位整數。
相關用法
- C# MathF.Min()用法及代碼示例
- C# MathF.Sin()用法及代碼示例
- C# MathF.Pow()用法及代碼示例
- C# MathF.Abs()用法及代碼示例
- C# MathF.Tan()用法及代碼示例
- C# MathF.Log()用法及代碼示例
- C# MathF.Cos()用法及代碼示例
- C# MathF.Max()用法及代碼示例
- C# MathF.Exp()用法及代碼示例
- C# File.Exists()用法及代碼示例
- C# File.SetCreationTime()用法及代碼示例
- C# File.SetCreationTimeUtc()用法及代碼示例
- C# File.SetLastWriteTime()用法及代碼示例
- C# File.GetAttributes()用法及代碼示例
- C# File.Move()用法及代碼示例
注:本文由純淨天空篩選整理自SoumikMondal大神的英文原創作品 Array.GetValue() Method in C# with Examples | Set – 2。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。