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# 中是什么意思?


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01