Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 为什么可以';设置循环算法的索引值?_C#_Algorithm_Loops - Fatal编程技术网

C# 为什么可以';设置循环算法的索引值?

C# 为什么可以';设置循环算法的索引值?,c#,algorithm,loops,C#,Algorithm,Loops,所以,基本上我在练习一些算法。我试图弄明白为什么下面的代码在我试图设置number[I]的值时给了我一个错误?我知道这可能很简单,但我不知道为什么它不起作用 public int SumOfRandomNumbersWithStrings(string randomness) { //Get the value of each index in the array string number = ""; for (int i = 0; i < randomness.

所以,基本上我在练习一些算法。我试图弄明白为什么下面的代码在我试图设置number[I]的值时给了我一个错误?我知道这可能很简单,但我不知道为什么它不起作用

public int SumOfRandomNumbersWithStrings(string randomness)
{
    //Get the value of each index in the array
    string number = "";
    for (int i = 0; i < randomness.Length; i++)
    {
        number[i] = randomness[i];
    }
    //temporarily one until I finish the algorithm
    return 1;
}
public int sumof随机数与字符串(字符串随机性)
{
//获取数组中每个索引的值
字符串编号=”;
for(int i=0;i
因为
数字
是空字符串。请改用连接运算符:

number = number + randomness[i];
为什么下面的代码在我尝试设置number[I]的值时出现错误

因为C#中的字符串是不可变的

但是,字符数组是可变的,因此可以执行以下操作:

char number[] = new char[randomness.Length];
for (int i = 0; i < randomness.Length; i++)
{
     number[i] = randomness[i];
}
string numStr = new string(number);
//temporarily one until I finish the algorithm
return 1;
char number[]=新字符[randomanness.Length];
for(int i=0;i

在C#中构建字符串最常见的方法是使用类。它允许您通过追加、删除或替换字符串中的字符来更改字符串的内容。

好的,如果您试图执行字符串连接,那么让我们将其更改为:

public int SumOfRandomNumbersWithStrings(string randomness) 
{ 
    StringBuilder sb = new StringBuilder();

    //Get the value of each index in the array 
    for (int i = 0; i < randomness.Length; i++) 
    { 
        sb.Append(randomness[i]);
    } 

    //temporarily one until I finish the algorithm 
    return 1; 
} 
public int SumOfRandomNumbersWithStrings(string randomness) 
{ 
    //Get the value of each index in the array 
    char[] number = new char[randomness.Length]; 
    for (int i = 0; i < randomness.Length; i++) 
    { 
        number[i] = randomness[i]; 
    } 

    //temporarily one until I finish the algorithm 
    return 1; 
} 

索引器只有get访问器,没有set访问器。就是这样的,duh。我忘了,这就是为什么我们有架线工。谢谢DasblinkenLight还有,对于您的第一个示例,您可能希望使用stringbuilder。谢谢@Servy,我已经更新了我的答案。我显然有点匆忙,我的道歉。