且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

什么"一个字段初始不能引用非静态字段"在C#是什么意思?

更新时间:2022-12-08 17:27:55

一个构造函数外使用的任何对象初始化有指静态成员,作为实例尚未建成之前,构造函数方式运行,运行任何构造函数之前直接变量的初始化概念发生。 getUserName是一个实例方法,但含实例不可用。



要解决这个问题,尝试将usernameDict初始化一个构造函数中。


I don't understand this error in C#

error CS0236: A field initializer cannot reference the non-static field, method, or property 'Prv.DB.getUserName(long)'

For the following code

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) { }
}

Any object initializer used outside a constructor has to refer to static members, as the instance hasn't been constructed until the constructor is run, and direct variable initialization conceptually happens before any constructor is run. getUserName is an instance method, but the containing instance isn't available.

To fix it, try putting the usernameDict initializer inside a constructor.