W1k*_*1k3 14 c# arrays string list
我正在尝试在C#中使用包含字符串数组的List,但我不知道如何正确地格式化我的声明.
private String encrypt(char[] text)
{
Random rnd = new Random();
string[] encrypted = new string[text.Length];
for (int i = 0; i < text.Length; i++)
{
int symnumb = rnd.Next(listmin, listmax);
encrypted[i] = alphabet[getnumber(text[i])][symnumb].ToString();
}
return string.Join("", encrypted);
}
Run Code Online (Sandbox Code Playgroud)
这进一步下降:
private int getnumber(char letter)
{
for (int i = 0; i < 27; i++)
{
if (letter == alphabetc[i])
{
return i;
}
}
return -1;
}
Run Code Online (Sandbox Code Playgroud)
我有很多不相关的代码来发布它,但"encrypted"是一个字符串数组,"alphabet"是包含字符串的数组列表.
声明:
public List<Array> alphabet = new List<Array>();
public char[] alphabetc = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', ' '};
Run Code Online (Sandbox Code Playgroud)
任何帮助都会很棒.
Sel*_*enç 19
错误很简单,你不能使用索引器Array
.Array
class是所有数组类型的基类,并且数组是从Array 隐式继承的.但是,Array
它本身没有索引器.以下是您的错误演示:
int[] numbers = new[] {1, 2, 3, 4, 5};
numbers[2] = 11; // Okay
Array arr = numbers as Array;
arr[2] = 11; // ERROR!
Run Code Online (Sandbox Code Playgroud)
因此,如果要使用索引器,请将元素类型更改为某个数组,例如:
public List<string[]> alphabet = new List<string[]>();
Run Code Online (Sandbox Code Playgroud)
Pet*_*eGO 12
尝试使用.ElementAt
.它适用于任何实现IEnumerable的东西,包括未编制索引的集合.
我已将您的陈述分成多个陈述,因此更容易识别违规行.
请注意 - ElementAt是一种扩展方法,您需要使用System.Linq
命名空间来使用它.
using System.Linq;
Run Code Online (Sandbox Code Playgroud)
然后在你的方法中:
var n = getnumber(text.ElementAt(i));
var items = alphabet.ElementAt(n);
encrypted[i] = items.ElementAt(symnumb).ToString();
Run Code Online (Sandbox Code Playgroud)
您不应该Array
在代码中使用该类型,因此请更改您的
public List<Array> alphabet = new List<Array>();
Run Code Online (Sandbox Code Playgroud)
进入例如
public List<string[]> alphabet = new List<string[]>();
Run Code Online (Sandbox Code Playgroud)
要么
public List<List<string>> alphabet = new List<List<string>>();
Run Code Online (Sandbox Code Playgroud)
如果你Array
出于某种原因坚持,你不能使用expr[i]
但必须这样做expr.GetValue(i)
,但是我不鼓励它,因为声明的返回类型是object
,并且你最终将进行大量的投射.