“字段初始化程序不能引用非静态字段"是什么意思?在 C# 中是什么意思? [英] What does "a field initializer cannot reference non static fields" mean in C#?

查看:22
本文介绍了“字段初始化程序不能引用非静态字段"是什么意思?在 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# 中是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆