让用户将值存储到字符串数组C#中
本文关键字:字符串 数组 存储 用户 | 更新日期: 2023-09-27 18:29:51
我在让用户将其值保存到数组中时遇到了一些问题,以下是我尝试使用的代码:如果可能的话,我希望能够存储多达4个对象,然后用null重置它们。
string [] array = new string[4];
array[i] += Console.ReadLine(); //and now it says: Cannot implicitly convert
type 'string' to 'int'. I also want to reset the value with this code:
array[i] = null;
我是阵列的新手,这真的很难。提前感谢!
问题出在类型为string
而不是int
的i
变量中。数组中的索引器需要使用整数值。
也没有理由使用+=
运算符。只需使用=
将您的值分配给数组元素即可。
var index = int.Parse(i); // the better way is to use TryParse to check your i string contains integer value
array[index] = Console.ReadLine();
在我看来,您似乎正在尝试使用名称对数组进行索引。如果是这样的话,我会使用Dictionary
:
var key = "MyValueKey"; //I presume this is currently your "i" value
var dict = new Dictionary<String, String>();
var userVal = Console.ReadLine();
if (String.IsNullOrWhitespace(userVal))
userVal = null;
if (dict.ContainsKey(key))
dict[key] = userVal;
else
dict.Add(key, userVal);