What does “a field initializer cannot reference no

2020-02-01 01:13发布

问题:

I don't understand this error in C#

error CS0236: A field initializer cannot reference the non-static field, method, or property '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) { }
}

回答1:

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.

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



回答2:

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



回答3:

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

OR

Initialize the dictionary in the constructor.



回答4:

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.



标签: c# delegates