当我运行Windows窗体应用程序时,它会显示initializer cannot reference the nonstatic field method or property
。
string lia = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
StreamReader fileitem=new StreamReader(Path.Combine(lia,"dataset.txt")); //Error line
我瘦,它无法将lia
识别为字符串。
有什么想法吗?
答案 0 :(得分:6)
我很瘦,它无法将lia识别为字符串。
不,它识别它很好 - 但是正如错误所说,你不能在初始化程序中使用一个实例变量的值用于另一个。
最简单的修复通常是将初始化放在构造函数中:
public class Foo
{
// TODO: Fix names to be more conventional and friendly
string lia = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
StreamReader fileitem;
public Foo()
{
fileitem=new StreamReader(Path.Combine(lia,"dataset.txt"));
}
}
另一方面,目前尚不清楚这些应该是字段......我们没有足够的上下文来确定,但也许您应该考虑这些是否应该方法中的局部变量,而不是类中声明的实例字段?