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# 中是什么意思?
基础教程推荐
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 如何激活MC67中的红灯 2022-01-01