我有一些使用文本文件的 C# 代码,我似乎无法让它与空白或空(空白)行一起正常工作。
我的代码:
while (!file.EndOfStream)
{
line = file.ReadLine();
bool isComment = (line[0] == '/') && (line[1] == '/');
bool isPoint = (line[0] == '(') && (line[line.Length - 1] == ')');
bool isWhiteSpace = string.IsNullOrEmpty(line);
Debug.Log("Comment: " + isComment + ", Point: " + isPoint + ", WhiteSpace: " + isWhiteSpace + "Value: '" + line + "'");
if (!isComment && !isPoint && !isWhiteSpace) { Application.Quit(); }
else if (isPoint)
{
//Strip parenthesis
line = line.Remove(line.Length - 1, 1).Remove(0, 1);
//break into float array
string[] arr = line.Split(',');
float xVal = float.Parse(arr[0]);
float yVal = float.Parse(arr[1]);
float zVal = float.Parse(arr[2]);
Vector3 currentVector = new Vector3(xVal, yVal, zVal);
results.Add(currentVector);
}
}
你可以看到我恰好在用 Vector3 做事。如果该行是注释行或空白行,我希望它什么也不做。如果它注意到括号,我希望它假设它是一个 Vector3 并解析它。最后,如果它不是这些线,我希望它完全停止。这是我仅使用记事本创建的示例文本文件:
//This is a comment
// ... and so is this!
(0, -1.5, 3)
(1, 4, 1.23)
(3, 5, 2)
请注意,第二个和第三个 Vector3 之间存在间隙。在这种特殊情况下,该行完全为空,不包含空格或任何内容,我只需在记事本中按 [Enter][Enter]。当我的脚本到达这一行时,它似乎触发了 file.EndOfStream boolean.... 但它不是文件的结尾!我怎样才能解决这个问题?我的 while 循环是否有更合适的条件?我还尝试读取该行并检查它是否为 null 作为 while 条件,这是一种更流行的处理方法,但这种处理方式也不适用于我的情况。
** 注意:“file”是 StreamReader 类型的变量 **