c# - Invalid token '=' in class, struct, or interface member declaration, Invalid token '(' in class, struct, or interface 成员声明

标签 c#

我想返回存储在数据库中的最后一条记录,并想将该返回值实例化给类 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();

 }

但它给出了上述错误。

最佳答案

您需要一个构造函数来为 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();
 }

关于c# - Invalid token '=' in class, struct, or interface member declaration, Invalid token '(' in class, struct, or interface 成员声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14409537/

相关文章:

c# - 我可以在 ListView 的详细信息模式下显示链接吗?

c# - 你用过的最酷的 C# LINQ/Lambdas 技巧?

c# - 自定义 AuthenticationHandler 在 Asp.Net Core 3 中不起作用

c# - 有没有办法对数组的一个成员以外的所有成员进行操作?

javascript - 选择选项时jquery提交选择表单

c# - 如何使用 C++ Logic 在 C# 或 VB 中创建接口(interface)

c# - 如何从 FIFO 队列中返回最新的对象而不删除它

C# JSON 如何读取具有未知父名称的特定值

c# - C# List<T> 的线程安全给读者

c# - 使用 C# 从 USB 读取数据?