错误:字段初始值设定项无法引用非静态字段,方法或属性

时间:2012-06-13 13:12:52

标签: c# field

我无法找到以下解决方案:

代码:

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();**
}

错误:

  

字段初始值设定项不能引用非静态字段,方法或属性

2 个答案:

答案 0 :(得分:7)

字段的初始值需要使用常量,静态字段/方法/属性或新实例。而是在构造函数中设置它:

class Data
{
    ApiData g;
    string vode;

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

答案 1 :(得分:1)

尝试制作提出此问题的字段static

//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);

希望这会有所帮助......