1

我找不到以下解决方案:

代码:

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

错误:

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

4

2 回答 2

7

字段的初始值需要使用常量、静态字段/方法/属性或新实例。相反,将其设置在您的构造函数中:

class Data
{
    ApiData g;
    string vode;

    public Data()
    {
        g = new ApiData();
        vode = g.code();
    }
}
于 2012-06-13T13:16:06.413 回答
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);

希望这可以帮助...

于 2013-09-13T14:21:49.877 回答