"字段初始值设定项不能引用非静态字段"在C#中意味着什么?

12 c# delegates

我不明白C#中的这个错误

错误CS0236:字段初始值设定项无法引用非静态字段,方法或属性'Prv.DB.getUserName(long)'

对于以下代码

public class MyDictionary<K, V>
{
    public delegate V NonExistentKey(K k);
    NonExistentKey nonExistentKey;

    public MyDictionary(NonExistentKey nonExistentKey_) { }
}

class DB
{
    SQLiteConnection connection;
    SQLiteCommand command;

    MyDictionary<long, string> usernameDict = new MyDictionary<long, string>(getUserName);

    string getUserName(long userId) { }
}
Run Code Online (Sandbox Code Playgroud)

the*_*oop 15

在构造函数外部使用的任何对象初始值设定项都必须引用静态成员,因为在构造函数运行之前尚未构造实例,并且在任何构造函数运行之前概念性地发生直接变量初始化.getUserName是一个实例方法,但包含的实例不可用.

要修复它,请尝试将usernameDict初始化程序放在构造函数中.


Ren*_*ene 8

下面的链接可能会说明为什么做你想要做的事情可能不是一件好事,特别是第二个环节:

为什么初始化器作为构造函数以相反的顺序运行?第一部分

为什么初始化器作为构造函数以相反的顺序运行?第二部分