class 中的无效标记“(”、记录、结构或接口成员声明

Invalid token '(' in class, record, struct or interface member declaration

我正在学习 Blazor 和 C#(两者都是新手)并且正在玩我的一个宠物项目。

对于该项目,我编写了一个 Project.cs 文件,该文件位于按照 this 教程创建的结构的 Data 目录中。

在某些时候,我需要一个字典数据结构,我尝试在 class 中创建这样的数据结构:

namespace MyApp.Data;

public class Project
{
    public Project()
    {
    }

    Dictionary<string, string> openWith =
    new Dictionary<string, string>();

    // Add some elements to the dictionary. There are no
    // duplicate keys, but some of the values are duplicates.
    openWith.Add("txt", "notepad.exe");
    openWith.Add("bmp", "paint.exe");
    openWith.Add("dib", "paint.exe");
    openWith.Add("rtf", "wordpad.exe");
}

但是我收到了错误 Invalid token '(' in class, record, struct, or interface member declaration 而我直接从微软的 documentation 中获取了这些行

我做错了什么?

你不能' 运行 class 中的任何代码。您可以将代码移至构造函数或特殊方法内,也可以直接使用 {}.

初始化 属性
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");

    }
}