【发布时间】:2021-05-30 21:27:31
【问题描述】:
我尝试创建一个函数,该函数打开配置文件,读取特定行以获取存储的值,然后将该值返回给调用子。因为我试图在 while 循环之外返回它,所以我得到了一个编译错误。我将如何获取存储值并将其设置为可以在命名空间中的其他地方使用的变量?
public class Functions
{
public static string GetODVPath()
{
//Read stored path of ODV.accdb file
string fileName = @"C:\Users\" + Environment.UserName + @"\ODV.conf";
using (StreamReader reader = new StreamReader(fileName))
{
string line;
while ((line = reader.ReadLine()) != null)
{
//if line length isnt 0 and line starts with [odv] set value of path
string odvPath = (line.Length != 0 && line.StartsWith("[ODV]")) ? line.Substring(4) : "";
}
return odvPath();
}
}
}
【问题讨论】:
-
你从函数中返回字符串的值。现在,您正试图将调用字符串变量的结果作为函数返回,这可能会引发异常。去掉括号,用合理的默认值在
while之外声明字符串odvPath,这样就可以了。 -
您要这样的东西吗?
string line; string odvPath = string.Empty; while ((line = reader.ReadLine()) != null) { odvPath = (line.Length != 0 && line.StartsWith("[ODV]")) ? line.Substring(4) : ""; } return odvPath;(在这种情况下,三元运算符没用,一个简单的 if 就足够了,但是您是要在找到的第一个处中断,还是取最后一个?)