我正在读取具有RGB值列表的文件,即
0,1,6
0,2,6
0,43,170
0,42,168
0,44,175
0,44,176
0,44,176
0,221,255
0,222,255
0,222,255
我已经string[]
使用以下构造函数将所有这些值存储到数组中:
public Program(int rows, String fileLocation) {
int i;
String line;
count = 0;
this.rows = rows;
this.fileLocation = fileLocation;
stringArray = new String[rows];
try {
System.IO.StreamReader file = new System.IO.StreamReader(fileLocation);
for (i = 0; i < rows; i++) {
while ((line = file.ReadLine()) != null) {
stringArray[i] = line;
count++;
break;
}
}
}
catch (Exception e) {
throw (e);
}
}
我想将这些current转换String
为Color
值,因为它们只是String形式的RGB值。
所以我用这种方法:
public Color[] convertToColorArray() {
for (int i = 0; i < rows; i++) {
colorArray[i] = System.Drawing.Color.FromArgb(stringArray[i]);
}
return colorArray;
}
话虽如此,我收到以下错误:
告诉我我有一个无效的参数。我知道该参数不一定是这样的255,255,255
,它ints
用逗号分隔三个,但是我的string
输入是这种格式。我该怎么办?我应该把它丢给什么吗?我是否应该一Color[]
开始就将这些值简单地存储到构造函数中?
查看的重载Color.FromArgb
,它们都希望int
被传递。因此,不能,您不能仅传递一个字符串并期望它可以工作。但是,将字符串转换为一组整数并不难。
public Color[] convertToColorArray() {
for (int i = 0; i < rows; i++) {
//This gives us an array of 3 strings each representing a number in text form.
var splitString = stringArray[i].Split(',');
//converts the array of 3 strings in to an array of 3 ints.
var splitInts = splitString.Select(item => int.Parse(item)).ToArray();
//takes each element of the array of 3 and passes it in to the correct slot
colorArray[i] = System.Drawing.Color.FromArgb(splitInts[0], splitInts[1], splitInts[2]);
}
return colorArray;
}
所有这些代码都假定您的源文件格式正确,因此string.Split
将始终返回至少3个数组,并且int.Parse
永远不会在解析输入时失败。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句