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

本文关键字:字段 静态 方法 属性 引用 不能 | 更新日期: 2023-09-27 18:36:29

我是C#的新手。我不明白为什么构造函数(constr)和_test1在这里出错?有人可以给我一个理解吗?

namespace ScratchPad
{
    class loading
    {
        public string _text1 = @"C:'Users'me'Documents'Defect DB'noemi.xlsx";

        string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + _text1 + ";Extended Properties='"Excel 12.0 XML;HDR=YES;IMEX=1'";"; 
        OleDbConnection con = new OleDbConnection(constr);
        var selectStatement = String.Format("Select * From [{0}$]", "excel");// _test2 is not working.
        OleDbDataAdapter adaptor = new OleDbDataAdapter(selectStatement, con);
        con.Open(); // if i leave _test1 like that then, this will fail.  private string _text1;
            DataTable table = new DataTable();
        adaptor.Fill(table);
     } 
}

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

尝试将代码放在类的构造函数中,但请记住,仅当您通过代码行加载 Loading = new Load() 创建 Loading 实例时,代码才会触发。另外,请在加载中大写 L。这是正确的类命名约定。

namespace ScratchPad
{
    class Loading
    {
     public string _text1;
     public string constr;
     public OleDbConnection con;
     public string selectStatement;
     public DataTable table;
        public Loading()
        {
        string _text1 = @"C:'Users'me'Documents'Defect DB'noemi.xlsx";

        constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + _text1 + ";Extended Properties='"Excel 12.0 XML;HDR=YES;IMEX=1'";"; 
        con = new OleDbConnection(constr);
        selectStatement = String.Format("Select * From [{0}$]", "excel");// _test2 is not working.
        OleDbDataAdapter adaptor = new OleDbDataAdapter(selectStatement, con);
        con.Open(); // if i leave _test1 like that then, this will fail.  private string _text1;
         table = new DataTable();
        adaptor.Fill(table);
        }
     } 
}