问题描述
我不明白 C# 中的这个错误
I don't understand this error in C#
错误 CS0236:字段初始值设定项无法引用非静态字段、方法或属性Prv.DB.getUserName(long)"
error CS0236: A field initializer cannot reference the non-static field, method, or property '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) { }
}
推荐答案
在构造函数之外使用的任何对象初始化器都必须引用静态成员,因为实例在构造函数运行之前还没有被构造,并且在概念上直接变量初始化在任何构造函数运行之前发生.getUserName 是一个实例方法,但包含的实例不可用.
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.
要修复它,请尝试将 usernameDict 初始化程序放在构造函数中.
To fix it, try putting the usernameDict initializer inside a constructor.
这篇关于“字段初始化程序不能引用非静态字段"是什么意思?在 C# 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!