如何在 C# 中从列表中获取布尔值<object>?



嗨,我正在将VB项目转换为MKAATR的YouTube教程C#他使用变量

 Private DBMSResultSets As List(Of Object)

所以我在c# private List<object> DBMSResultSets;

中使用了一个变量

和以后的代码,他使用返回类型bool的函数,他使用方法

return DBMSResultSets(I).Read

所以我使用同样的事情,但是Visual Studio给我错误,因此悬停在VB代码(DBMSResultSets(I).Read)上说"获取或设置元素"在

现在,Visual Studio给我错误,无法将对象转换为Bool,因此我使用convert.to。所以我需要帮助我给您整个VB代码,也给我的转换C#代码

问题在于功能readandnoteof

VB代码

Imports System.Data.SqlClient
    
    ' this class will be used to manage connectivity with the database
    Public Class DBMSClass
    
        ' define the connection string
        Private DBMSConnectionString = "Data Source=.SQLEXPRESS;AttachDbFilename=C:UsersAsusDesktopLibraryManagementSystemDatabaseLMS.mdf;Integrated Security=True;User Instance=True;MultipleActiveResultSets=true"
    
        ' define the connection
        Private DBMSConnectionObj As System.Data.SqlClient.SqlConnection
    
        ' define the transaction
        Private DBMSTransactionObj As System.Data.SqlClient.SqlTransaction
    
        ' define the commands object and result sets
        Private DBMSCommands As List(Of System.Data.SqlClient.SqlCommand)
        Private DBMSCommandCodes As List(Of Long)
        Private DBMSResultSets As List(Of Object)
    
        ' command counter
        Private DBMSCommandCounter As Long
    
        ' open database connection
        Public Function OpenDB() As String
            Try
                ' open the connection
                DBMSConnectionObj = New SqlConnection(My.Settings.myconnection)
                DBMSConnectionObj.Open()
    
                ' create the transaction
                DBMSTransactionObj = DBMSConnectionObj.BeginTransaction
    
                ' prepare the commands list
                DBMSCommands = New List(Of System.Data.SqlClient.SqlCommand)
                DBMSCommandCodes = New List(Of Long)
                DBMSResultSets = New List(Of Object)
    
                ' prepare the command counter
                DBMSCommandCounter = 0
    
                ' return ok
                Return "OK"
            Catch ex As Exception
                Return ex.Message
            End Try
        End Function
    
        ' this is used to run sql commands
        Public Sub ExecuteSQL(ByVal SQL As String, ByVal ParamArray Obj() As Object)
    
            ' build the command object
            Dim CMD As New System.Data.SqlClient.SqlCommand(SQL, Me.DBMSConnectionObj, Me.DBMSTransactionObj)
    
            ' add the parameters to the sql command
            Dim I As Integer
            For I = 0 To Obj.Length - 1
                CMD.Parameters.AddWithValue("@" & I, Obj(I))
            Next
    
            ' run the sql
            CMD.ExecuteNonQuery()
    
        End Sub
    
        ' this function is used to commit a transaction
        Public Sub Commit()
            Me.DBMSTransactionObj.Commit()
            Me.DBMSTransactionObj = Me.DBMSConnectionObj.BeginTransaction
        End Sub
    
        ' this function is used to rollback a transaction
        Public Sub Rollback()
            Me.DBMSTransactionObj.Rollback()
            Me.DBMSTransactionObj = Me.DBMSConnectionObj.BeginTransaction
        End Sub
    
        ' this function is used to create a result set
        Public Function CreateResultSet(ByVal SQL As String, ByVal ParamArray OBJ() As Object) As Long
            DBMSCommandCounter += 1
    
            ' build the command object
            Dim CMD As New System.Data.SqlClient.SqlCommand(SQL, Me.DBMSConnectionObj, Me.DBMSTransactionObj)
    
            ' add the parameters to the sql command
            Dim I As Integer
            For I = 0 To OBJ.Length - 1
                CMD.Parameters.AddWithValue("@" & I, OBJ(I))
            Next
    
            ' read the data
            Dim RS = CMD.ExecuteReader(CommandBehavior.Default)
    
            ' store objects in list
            Me.DBMSCommandCodes.Add(DBMSCommandCounter)
            Me.DBMSCommands.Add(CMD)
            Me.DBMSResultSets.Add(RS)
    
            Return DBMSCommandCounter
        End Function
    
        ' this function is used to close a result set
        Public Sub CloseResultSet(ByVal Nmbr As Long)
            Dim I As Integer
            For I = 0 To Me.DBMSCommandCodes.Count - 1
    
                ' find the command and result set
                If DBMSCommandCodes(I) = Nmbr Then
    
                    ' get the objects
                    Dim R = Me.DBMSResultSets(I)
                    Dim C = Me.DBMSCommands(I)
    
                    ' remove the objects from the list
                    Me.DBMSResultSets.RemoveAt(I)
                    Me.DBMSCommands.RemoveAt(I)
                    Me.DBMSCommandCodes.RemoveAt(I)
    
                    ' return the resources
                    R.Close()
                    R.Dispose()
                    C.Dispose()
    
                    Return
    
                End If
            Next
    
            Throw New Exception("the command or result set does not exist")
        End Sub
    
        ' this function is used to read a single record from db
        Public Function ReadAndNotEOF(ByVal Code As Long) As Boolean
            ' do a search
            Dim I As Long
            For I = 0 To Me.DBMSCommandCodes.Count - 1
                If DBMSCommandCodes(I) = Code Then
                    Return DBMSResultSets(I).Read
                End If
            Next
            Throw New Exception("Command or Resultset does not exist")
        End Function
    
        ' this function is used to get a column value from db
        Public Function GetColumnValue(ByVal Code As Long, ByVal ColumnName As String) As Object
            Dim I As Long
            For I = 0 To Me.DBMSCommands.Count - 1
                If DBMSCommandCodes(I) = Code Then
                    Return DBMSResultSets(I).Item(ColumnName)
                End If
            Next
            Throw New Exception("Command or Resultset does not exist")
        End Function
    End Class

我的C#代码

//this class will be used to manage connectivity with the database
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Sql;
using System.Data;
using System.Data.SqlClient;
namespace Library_main
{
    public class DBMSClass
    {
        //define the connection string
        // private String DBMSConnectionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename="\D:\tutorial\c # tutorial\3 may 2015\Library_main\Library_main\bin\Debug\DataBase\LMS.mdf";"Integrated Security=True;Connect Timeout=30";
        //define the connection
        private SqlConnection DBMSConnectionObj = null;
        //define the transaction
        private SqlTransaction DBMSTransactionObj;
        // define the commands object and result sets
        private List<SqlCommand> DBMSCommands;
        private List<long> DBMSCommandCodes;
        private List<object> DBMSResultSets;
        // command counter
        private long DBMSCommandCounter;
        //open database connection
        public string OpenDB()
        {
            try
            {
                //open the connection
                DBMSConnectionObj = new SqlConnection(Properties.Settings.Default.ConnectionString);
                DBMSConnectionObj.Open();
                //creat the transaction
                DBMSTransactionObj = DBMSConnectionObj.BeginTransaction();
                //prepare the commands list
                DBMSCommands = new List<SqlCommand>();
                DBMSCommandCodes = new List<long>();
                DBMSResultSets = new List<object>();
                // prepare the command counter
                DBMSCommandCounter = 0;
                //return ok
                return "ok";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        //this is used to run sql commands
        public void ExceuteSQL(string SQL, params object[] Obj)
        {
            //build the command object
            SqlCommand CMD = new SqlCommand(SQL, this.DBMSConnectionObj, this.DBMSTransactionObj);
            //add the parameters to the sql command
            int I;
            int count = Obj.Length - 1;
            for (I = 0; I <= count; I++)
            {
                CMD.Parameters.AddWithValue("@" + I, Obj[I]);
            }
            //run the sql
            CMD.ExecuteNonQuery();
        }
        //this funtion to commit 
        public void Commit()
        {
            this.DBMSTransactionObj.Commit();
            this.DBMSTransactionObj = this.DBMSConnectionObj.BeginTransaction();
        }
        // this function is used to rollback a transaction
        public void Rollback()
        {
            this.DBMSTransactionObj.Rollback();
            this.DBMSTransactionObj = this.DBMSConnectionObj.BeginTransaction();
        }
        //this function is used to creat a result set
        public long CreatResultSet(string SQL, params object[] Obj)
        {
            DBMSCommandCounter += 1;
            // build the command object
            SqlCommand CMD = new SqlCommand(SQL, this.DBMSConnectionObj, this.DBMSTransactionObj);
            // add the parameters to the sql command
            int I = 0;
            for (I = 0; I <= Obj.Length - 1; I++)
            {
                CMD.Parameters.AddWithValue("@" + I, Obj[I]);
            }
                // read the data
                dynamic RS = CMD.ExecuteReader(System.Data.CommandBehavior.Default);
                // store objects in list
                this.DBMSCommandCodes.Add(DBMSCommandCounter);
                this.DBMSCommands.Add(CMD);
                this.DBMSResultSets.Add(RS);
            return DBMSCommandCounter;
        }
        // this function is used to close a result set
        public void CloseResultSet(long Nmbr)
        {
            int I = 0;
            for (I = 0; I <= this.DBMSCommandCodes.Count - 1; I++)
            {
                // find the command and result set
                if (DBMSCommandCodes[I] == Nmbr)
                {
                    // get the objects
                    dynamic R = this.DBMSResultSets[I];
                    dynamic C = this.DBMSCommands[I];
                    // remove the objects from the list
                    this.DBMSResultSets.RemoveAt(I);
                    this.DBMSCommands.RemoveAt(I);
                    this.DBMSCommandCodes.RemoveAt(I);
                    // return the resources
                    R.Close();
                    R.Dispose();
                    C.Dispose();
                    return;
                }
            }
            throw new Exception("the command or result set does not exist");
        }
        // this function is used to read a single record from db
        public bool ReadAndNotEOF(long Code)
        {
            // do a search
            long I = 0;
            for (I = 0; I <= this.DBMSCommandCodes.Count - 1; I++)
            {
                if (DBMSCommandCodes[(int)I] == Code)
                {
                    return Convert.ToBoolean(DBMSResultSets[(int)I]);
                }
            }
            throw new Exception("Command or Resultset does not exist");
        }
        // this function is used to get a column value from db
        public object GetColumnValue(long Code, string ColumnName)
        {
            long I = 0;
            for (I = 0; I <= this.DBMSCommandCodes.Count - 1; I++)
           
                if (DBMSCommandCodes[(int)I] == Code)
                {
                    return DBMSResultSets[(int)I].Equals(ColumnName);
                }
            
            throw new Exception("Command or Resultset does not exist");
        }
    }
}

在sqlcommand对象上调用executereader的结果是 SqlDataReader

请参阅此处

在您的代码的这一部分中

// read the data
dynamic RS = CMD.ExecuteReader(System.Data.CommandBehavior.Default);
// store objects in list
this.DBMSCommandCodes.Add(DBMSCommandCounter);
this.DBMSCommands.Add(CMD);
this.DBMSResultSets.Add(RS);

RS的类型与ResultSet的确切等效范围不像 CC_5所建议的,但它是一个具有布尔方法的SqlDataReader,它具有boolean方法调用Read,它将返回true,直到没有更多的数据从其流中获取

所以在您的布尔方法中,称为 ReadAndNotEof而不是

return Convert.ToBoolean(DBMSResultSets[(int)I]);

SqlDataReader reader = (SqlDataReader)DBMSResultSets[(int)I];
return reader.Read();

以相同的模式,如果您的更改,您可以在方法getColumnValue中获得列值:

return DBMSResultSets[(int)I].Equals(ColumnName);

SqlDataReader reader = (SqlDataReader)DBMSResultSets[(int)I];
object columnValue = reader[columnName];
return columnValue;

请参阅MSDN上的访问者this(如读取器[string_value])的定义,该定义采用字符串参数(列名)

当然,您需要确保您的sqldatareader的读取方法已返回(您的上述方法)

希望这对您有帮助。

相关内容

  • 没有找到相关文章

最新更新