C#编写JSON读取类时无故提示缺括号等编译错误如何解决
问题原因分析
- 核心错误1:构造函数内的局部变量错误使用访问修饰符
C#中public/private这类访问修饰符仅可用于类的成员(字段、属性、方法、嵌套类等)定义,构造函数属于类的方法,方法内部声明的变量是局部变量,作用域仅存在于方法内部,不允许加访问修饰符。你在构造函数内写的public string filename = fileName;和private string contents = System.IO.File.ReadAllLines(fileName);违反了这个语法规则,编译器会误以为你要定义类成员、当前构造函数已经结束,因此后续的if语句等都会被识别为非法的类成员声明,同时抛出缺}的报错。 - 次要错误2:类型不匹配
System.IO.File.ReadAllLines()方法返回值是string[](字符串数组),你用string类型的变量接收,就算解决修饰符问题也会触发编译报错。 - 额外隐含问题:
File.Create()方法会返回一个打开的FileStream对象,如果不主动释放,后续读取文件时会触发文件被占用的IO错误。
解决方案
根据你的使用需求选择以下任意一种修改方案即可:
方案1:将变量定义为类成员(需要在构造函数外访问这两个变量时使用)
把变量的定义移到构造函数外部作为类成员,构造函数内仅做赋值操作:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Blackjack { class LeaderBoard { // 类成员定义在构造函数外部,可正常加访问修饰符 public string filename; // ReadAllLines返回字符串数组,类型修正为string[] private string[] contents; LeaderBoard(string fileName) { filename = fileName; if (!File.Exists(fileName)) { // 创建文件后立即释放流,避免后续读取报错 File.Create(fileName).Dispose(); } contents = File.ReadAllLines(fileName); } } }
方案2:变量仅在构造函数内使用时
直接删除变量前的访问修饰符,同时修正contents的类型即可:
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Blackjack { class LeaderBoard { LeaderBoard(string fileName) { // 局部变量不需要加访问修饰符 string filename = fileName; if (!File.Exists(fileName)) { File.Create(fileName).Dispose(); } // 类型修正为string[] string[] contents = File.ReadAllLines(fileName); } } }
内容的提问来源于stack exchange,提问作者krystof18
相关产品推荐
相关产品推荐

