Error: A field initializer cannot reference the non-static field, method, or property

二次信任 提交于 2019-12-23 04:39:17

问题


I can't find a solution for the following:

Code:

class ApiData

{ SqlCeConnection conn = new SqlCeConnection(@"Data Source=C:\Users\Peter\Documents   \db.sdf;");

SqlCeCommand cmd = null;
    SqlCeDataReader rdr = null;
    public string code()
    {
        conn.Open();
        cmd = conn.CreateCommand();
        cmd.CommandText ="SELECT code FROM Charakter WHERE id=1";
        rdr = cmd.ExecuteReader();
        rdr.Read();
        string selected = rdr.GetString(0);
        conn.Close();
        return (selected);
    }
class Data{
  ApiData g= new ApiData();
    string vode = **g.code();**
}

Error:

A field initializer cannot reference the non-static field, method, or property


回答1:


Try making the field static which was giving this issue

//INITIALLY this field was non-static 
//public string ConnectionString = "Data Source=ServerName;Initial Catalog=DBname;User Id=user_id;Password=password";

//Make this field static
public static string ConnectionString = "Data Source=ServerName;Initial Catalog=DBname;User Id=user_id;Password=password";
static SqlConnection sqlConnection = new SqlConnection(ConnectionString);

Hope this helps...




回答2:


The initial values for fields need to use constants, static fields/methods/properties, or new instances. Instead, set it in your constructor:

class Data
{
    ApiData g;
    string vode;

    public Data()
    {
        g = new ApiData();
        vode = g.code();
    }
}


来源:https://stackoverflow.com/questions/11015591/error-a-field-initializer-cannot-reference-the-non-static-field-method-or-pro

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!