2016-01-11 32 views
-3

我遇到了一些麻烦,让用户节省了他的价值到一个数组,下面是我试过的代码: 我希望能够存储多达4个对象,然后用null重置它们(如果可能的话)。让用户存储值转换成字符串数组C#

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; 

我是新来的阵列,它真的很难。提前致谢!

+6

'i'从哪里来?想必你想'='而不是'+ ='但还有你的错误看起来更有可能做'i' – Sayse

+0

我想“我”站了指数,所以我用它来储存字符串到我的数组@Sayse – Alex

+1

'i'指的是通常用来表示一个索引的变量名,但是这取决于你如何定义它 – Sayse

回答

0

问题出在i变量有一个类型string而不是int。您需要为数组中的索引器使用整数值。

也没有理由使用+=运营商。只需使用=将您的值分配给数组元素。

var index = int.Parse(i); // the better way is to use TryParse to check your i string contains integer value 
array[index] = Console.ReadLine(); 
-1

在我看来,你正在尝试索引使用名称的数组。如果是这样,我会用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); 
+0

是否downvoter有一个理由,或者只是曳? – DonBoitnott