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

查看:364
本文介绍了什么"一个字段初始不能引用非静态字段"在C#是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不明白,在C#中此错误




错误CS0236:一个字段初始不能引用非静态字段,方法,或属性Prv.DB.getUserName(长)




有关下面的代码

 公共类MyDictionary< K,V> 
{
公共委托V NonExistentKey(K K);
NonExistentKey nonExistentKey;

公共MyDictionary(NonExistentKey nonExistentKey_){}
}

类DB
{
SQLiteConnection连接;
SQLiteCommand命令;

MyDictionary<长,弦> usernameDict =新MyDictionary<长,弦>(getUserName);

串getUserName(长用户id){}
}


解决方案

一个构造函数外使用的任何对象初始化有指静态成员,作为实例尚未建成之前,构造函数方式运行,运行任何构造函数之前直接变量的初始化概念发生。 getUserName是一个实例方法,但含实例不可用。



要解决这个问题,尝试将usernameDict初始化一个构造函数中。


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

解决方案

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.

这篇关于什么&QUOT;一个字段初始不能引用非静态字段&QUOT;在C#是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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