C#是否有与PHP的array_key_exists函数相等的功能?
例如,我有这个PHP代码:
$array = array();
$array[5] = 4;
$array[7] = 8;
if (array_key_exists($array, 2))
echo $array[2];
我该如何将这个转换成C#代码?
C#是否有与PHP的array_key_exists函数相等的功能?
例如,我有这个PHP代码:
$array = array();
$array[5] = 4;
$array[7] = 8;
if (array_key_exists($array, 2))
echo $array[2];
int[] array = new int[8];
if(array.Length > 2)
{
Debug.WriteLine( array[2] );
}
Person[] array = new Person[8];
if(array.Length > 2 && array[2] != null)
{
Debug.WriteLine( array[2].ToString() );
}
using System.Collections.Generic;
...
Dictionary<int, int> dict = new Dictionary<int, int>();
dict.Add(5, 4);
dict.Add(7, 8);
if (dict.ContainsKey(5))
{
// [5, int] exists
int outval = dict[5];
// outval now contains 4
}
$arr[0]
和$arr[2]
,但$arr[1]
未定义。 - Cole Tobin在C#中声明新数组时,需要提供内存分配的大小。如果你正在创建一个int
数组,则在实例化时会预先填充值,因此键将始终存在。
int[] array = new int[10];
Console.WriteLine(array[0]); //outputs 0.
List
。List<int> array = new List<int>
array.push(0);
if (array.Length > 5)
Console.WriteLine(array[5]);
您可以使用 ContainsKey
var dictionary = new Dictionary<string, int>()
{
{"mac", 1000},
{"windows", 500}
};
// Use ContainsKey method.
if (dictionary.ContainsKey("mac") == true)
{
Console.WriteLine(dictionary["mac"]); // <-- Is executed
}
// Use ContainsKey method on another string.
if (dictionary.ContainsKey("acorn"))
{
Console.WriteLine(false); // <-- Not hit
}
数组
,我想知道是否包含所选键上的值” -数组
没有键
啊! - web_bod