What does quot;a field initializer cannot reference non static fieldsquot; mean in C#?(“字段初始化程序不能引用非静态字段是什么意思?在 C# 中是什么意思?)
问题描述
我不明白 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# 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“字段初始化程序不能引用非静态字段"是什么意思?在 C# 中是什么意思?


- C# 中多线程网络服务器的模式 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01