Blazor C#类中定义Dictionary报Invalid token '('错误求助
问题原因与解决方案
错误触发原因
C#语法规定,方法调用这类可执行代码不能直接放置在类的成员声明层级,仅能在构造函数、普通方法、属性访问器、代码块或者字段/属性的初始化表达式中执行。
你代码里的openWith.Add()属于方法调用,直接写在了类的成员区域,不符合语法规范,因此触发了编译错误。
两种可行修复方案
方案一:将字典元素添加逻辑移入构造函数
你已经定义了空的Project构造函数,直接把Add相关的执行代码放到构造函数内部即可:
using System.Collections.Generic; namespace MyApp.Data; public class Project { // 类成员层级仅做字段声明和初始化 Dictionary<string, string> openWith = new Dictionary<string, string>(); public Project() { // 可执行代码放在构造函数内 openWith.Add("txt", "notepad.exe"); openWith.Add("bmp", "paint.exe"); openWith.Add("dib", "paint.exe"); openWith.Add("rtf", "wordpad.exe"); } }
方案二:使用集合初始化器声明时直接赋值
如果不需要额外的逻辑判断,直接在字段声明时用集合初始化器完成赋值,语法更简洁:
using System.Collections.Generic; namespace MyApp.Data; public class Project { Dictionary<string, string> openWith = new Dictionary<string, string>() { { "txt", "notepad.exe" }, { "bmp", "paint.exe" }, { "dib", "paint.exe" }, { "rtf", "wordpad.exe" } }; public Project() { } }
注意:如果文件顶部没有引入集合命名空间,需要补充
using System.Collections.Generic;,否则会出现Dictionary类型找不到的报错。
内容的提问来源于stack exchange,提问作者FenryrMKIII
相关产品推荐
相关产品推荐

