“字段初始值设定项不能引用非静态字段”在 C# 中是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/923343/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 03:17:55  来源:igfitidea点击:

What does "a field initializer cannot reference non static fields" mean in C#?

c#delegates

提问by

I don't understand this error in C#

我不明白 C# 中的这个错误

error CS0236: A field initializer cannot reference the non-static field, method, or property 'Prv.DB.getUserName(long)'

错误 CS0236:字段初始值设定项无法引用非静态字段、方法或属性“Prv.DB.getUserName(long)”

For the following code

对于以下代码

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) { }
}

采纳答案by thecoop

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.

在构造函数之外使用的任何对象初始值设定项都必须引用静态成员,因为在运行构造函数之前尚未构造实例,并且直接变量初始化在概念上发生在任何构造函数运行之前。getUserName 是一个实例方法,但包含的实例不可用。

To fix it, try putting the usernameDict initializer inside a constructor.

要修复它,请尝试将 usernameDict 初始值设定项放在构造函数中。

回答by shahkalpesh

getUserName is an instance method.
Change it to static, that might work.

getUserName 是一个实例方法。
将其更改为静态,这可能会奏效。

OR

或者

Initialize the dictionary in the constructor.

在构造函数中初始化字典。

回答by zoidbeck

You cannot do this because the instance has to be initialized before you can access the properties of its class. The field initializers are called before the class is initialized.

您不能这样做,因为必须先初始化实例,然后才能访问其类的属性。字段初始化器在类初始化之前被调用。

If you want to initialize the field usernameDict with the return-value of the GetUserName-Method you have to do it within the constructor or make the Method a static one.

如果要使用 GetUserName-Method 的返回值初始化字段 usernameDict,则必须在构造函数中执行此操作或将 Method 设为静态方法。

回答by Rene

The links below may shed some light on why doing what you are trying to do may not be such a good thing, in particular the second link:

下面的链接可能会说明为什么做你想做的事情可能不是一件好事,特别是第二个链接:

Why Do Initializers Run In The Opposite Order As Constructors? Part One

为什么初始化程序与构造函数的运行顺序相反?第一部分

Why Do Initializers Run In The Opposite Order As Constructors? Part Two

为什么初始化程序与构造函数的运行顺序相反?第二部分