字段初始值设定项不能引用非静态字段c#

时间:2015-02-17 08:46:21

标签: c# winforms

我想从textdocument获取服务器详细信息,因此我将参数(loacalhost)传递给connectionstring。但发生以下错误。

  

“字段初始值设定项不能引用非静态字段”

public partial class Form1: Form
{

    public Form1()
    {
        InitializeComponent();
        labelget();

    }
     string localhost ;
     string myconnectionstring = "Server=" + localhost + "; Database=amepos2015; Uid=root; Pwd=fatehshah";  /*error on this line */

     public void labelget()
     {

             using (StreamReader sr = new StreamReader("C:/Requirement.txt"))
             {
                 while ((localhost = sr.ReadLine()) != null)
                 {
                     localhost = sr.ReadLine();
                 }
             }
         }
         catch (Exception ea)
         {
             if (MessageBox.Show("File not found", "Error", MessageBoxButtons.OK) == DialogResult.OK)
             {
                 Application.Exit();
             }
         }
         Console.Read();
     }
}

2 个答案:

答案 0 :(得分:3)

您无法在类中连接多个字符串字段来初始化它们,因为it is not allowed that the variable initializer for an instance field references the instance being created(与其他属性或字段一样)。

请改用构造函数:

public Form1()
{
    InitializeComponent();

    localhost = "blah ..."; // initialize this string
    myconnectionstring = "Server=" + localhost + "; Database=amepos2015; Uid=root; Pwd=fatehshah";  

    labelget();
}

string localhost = null;
string myconnectionstring = null;

原因是编译器希望防止您在更改字段顺序时发生的错误。因此,首先不允许这样做。

答案 1 :(得分:0)

代码中myconnectionstring变量的初始化不正确,因为它依赖于另一个非静态变量。 要解决此问题,只需将myconnectionstring变量的初始化放入类构造函数中。有关此错误的详细信息,请参阅this link