使用 "foreach" 语句将字符串数组的索引值设置为可枚举数组中某项的索引值。
Setting the value of an index of a string array to that of an item within an Enumerable array by using a "foreach" statement.
这是将字符串数组的每一项设置为可枚举数组的每一项的最佳方法吗?我自己想出了这种方法,我尝试使用我的 google-foo 但无法真正想出连贯的句子来描述我在这里尝试做的事情..
string[] adapterDesc = new string[] {};
int i = 0;
foreach(NetworkInterface adapter in adapters)
{
adapterDesc[i] = adapter.Description;
i++;
}
...
不,该代码将失败并出现 IndexOutOfRange
异常,因为您声明了一个可能包含零个元素的字符串数组。
所以当你尝试设置第一个元素时它会崩溃。
相反,您可以使用可以动态添加元素的列表
List<string> adapterDesc = new List<string>();
foreach(NetworkInterface adapter in adapters)
{
adapterDesc.Add(adapter.Description);
}
...
列表比数组更灵活,因为您不必事先知道数组的大小,您仍然可以像使用数组一样使用它
for(int x = 0; x < adapterDesc; x++)
{
Console.WriteLine(adapterDesc[x]);
}
如果您想使用 Linq,那么您甚至可以使用
将您的代码减少到一行
string[] adapterDesc = NetworkInterface.GetAllNetworkInterfaces()
.Select(ni => ni.Description)
.ToArray();
这是将字符串数组的每一项设置为可枚举数组的每一项的最佳方法吗?我自己想出了这种方法,我尝试使用我的 google-foo 但无法真正想出连贯的句子来描述我在这里尝试做的事情..
string[] adapterDesc = new string[] {};
int i = 0;
foreach(NetworkInterface adapter in adapters)
{
adapterDesc[i] = adapter.Description;
i++;
}
...
不,该代码将失败并出现 IndexOutOfRange
异常,因为您声明了一个可能包含零个元素的字符串数组。
所以当你尝试设置第一个元素时它会崩溃。
相反,您可以使用可以动态添加元素的列表
List<string> adapterDesc = new List<string>();
foreach(NetworkInterface adapter in adapters)
{
adapterDesc.Add(adapter.Description);
}
...
列表比数组更灵活,因为您不必事先知道数组的大小,您仍然可以像使用数组一样使用它
for(int x = 0; x < adapterDesc; x++)
{
Console.WriteLine(adapterDesc[x]);
}
如果您想使用 Linq,那么您甚至可以使用
将您的代码减少到一行string[] adapterDesc = NetworkInterface.GetAllNetworkInterfaces()
.Select(ni => ni.Description)
.ToArray();