【问题标题】:Invalid token '=' in class, struct, or interface member declaration, Invalid token '(' in class, struct, or interface member declaration类、结构或接口成员声明中的无效标记“=”,类、结构或接口成员声明中的无效标记“(”
【发布时间】:2013-01-02 18:57:27
【问题描述】:

我想返回存储在数据库中的最后一条记录,并希望将该返回值实例化为 ReligionCaste 类的成员 pID, 但我有标题错误。

我的数据库函数是

public int LastEnteredRecord()
    {
        int lastId=0;
        dbConnection = new SqlConnection(connectionString);
        try    //If error in connection opening, throws it.
        {
            dbConnection.Open();
            command.Connection = dbConnection;
            command.CommandType = CommandType.StoredProcedure;
            command.CommandText = "dbo.LastRecordEntered";


            try    //if error in query execution, throws it.
            {
                lastId= Convert.ToInt32 ( command.ExecuteScalar());
               // MessageBox.Show("Record Entered with ID:"+lastId .ToString ());
            }
            catch (SqlException ex)
            {
                MessageBox.Show(ex.Message);

            }
            dbConnection.Close();
            dbConnection.Dispose();
        }
        catch (SqlException ex)
        {
            MessageBox.Show(ex.Message);

        }
        return lastId;
    }  

我想将该返回值分配给代码所在的类

class ReligionCaste
{
    //public int religion_ID, caste_ID;
    public String religion, sect, caste, subCaste;
    public int pID;

    DatabaseHandler.DBCntrlr dbObj = new DatabaseHandler.DBCntrlr();
    pID = dbObj.LastEnteredRecord();

 }

但它给出了上述错误。

【问题讨论】:

  • 哪里抛出了异常?该异常告诉我,当您给它一个 = 时,IDE 期待一个 == 并且在某处也有一个尾随 (
  • 错误来自你的 Catch 吗?

标签: c#


【解决方案1】:

您需要一个构造函数来为 pId 赋值,此时您的语法无效。示例:

class ReligionCaste
{
    public ReligionCaste()
    {
        pID = dbObj.LastEnteredRecord();
    }

    //public int religion_ID, caste_ID;
    public String religion, sect, caste, subCaste;
    public int pID;

    DatabaseHandler.DBCntrlr dbObj = new DatabaseHandler.DBCntrlr();
 }

【讨论】:

  • 不错的收获。我完全错过了!
【解决方案2】:
class ReligionCaste
{
    //public int religion_ID, caste_ID;
    public String religion, sect, caste, subCaste;
    public int pID;
    private DatabaseHandler.DBCntrlr dbObj;

    public ReligionCaste()
    {
        dbObj = new DatabaseHandler.DBCntrlr();
        pID = dbObj.LastEnteredRecord();
    }  
 }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-07
    • 2014-06-22
    • 2016-07-10
    • 1970-01-01
    • 2012-06-19
    • 2014-02-02
    相关资源
    最近更新 更多