简体   繁体   English

类,结构或接口成员声明中的标记'='无效,类,结构或接口成员声明中的无效标记'('

[英]Invalid token '=' in class, struct, or interface member declaration, Invalid token '(' in class, struct, or interface member declaration

I want to return a last record stored in database and want to instantiate that returned value to the class ReligionCaste's member pID, But i have the title error. 我想返回存储在数据库中的最后一条记录,并希望将返回值实例化为ReligionCaste类的成员pID,但我有标题错误。

My database function is 我的数据库功能是

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;
    }  

I want to assign that return value to a class instant the code is 我想将该返回值分配给代码所在的类

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

 }

but it giving the above mentioned error. 但它给出了上述错误。

You need a constructor to assign a value to pId, at the moment your syntax is invalid. 在语法无效时,您需要一个构造函数为pId赋值。 Example: 例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM