【问题标题】:Error: A field initializer cannot reference the non-static field, method, or property错误:字段初始值设定项无法引用非静态字段、方法或属性
【发布时间】:2012-06-13 13:12:52
【问题描述】:

我找不到以下问题的解决方案:

代码:

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

错误:

字段初始化器不能引用非静态字段、方法或属性

【问题讨论】:

标签: c# field


【解决方案1】:

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

class Data
{
    ApiData g;
    string vode;

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

【讨论】:

  • “字段的初始值需要使用常量”——没有那么严格;它们还可以引用静态字段、方法或属性。但解决方案是对的,+1。
  • 谢谢,我以前试过这个,但忘记了“字符串 vcode;”线。我在 c#^^ 上什么也没做太久
【解决方案2】:

尝试填写导致此问题的字段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);

希望这会有所帮助...

【讨论】:

  • 为什么连接字符串需要是静态的?
  • @umeshsohaliya 这是一个很老的答案,可能我可能已经在我们的一个项目中做了一些尝试。
猜你喜欢
  • 2019-04-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-16
  • 2013-01-04
  • 2022-01-23
相关资源
最近更新 更多