vb.net code USING and WITH c# 的代码是什么

vb.net code USING and WITH what is the code for c#

所以我正在尝试学习 C#,因为我想改变我的旧编程技能,即 vb.net 我正在打开一些转换器站点,但它不起作用。我只想知道vb.net中USING和WITH的代码转c#.

这是我在 vb.net 中的代码:

Dim rand As New Random
    abuildnumber.Text = rand.Next
    Dim exist As String = String.Empty
    exist &= "select * from stocks "
    exist &= "where build_number=@build"
    Using conn As New SqlConnection("server=WIN10;user=admin;password=12345;database=pc_parts")
        Using cmd As New SqlCommand
            With cmd
                .Connection = conn
                .CommandType = CommandType.Text
                .CommandText = exist
                .Parameters.AddWithValue("@build", abuildnumber.Text)
            End With
            Try
                conn.Open()
                Dim reader As SqlDataReader = cmd.ExecuteReader
                If reader.HasRows Then
                    reader.Close()
                    abuildnumber.Text = rand.Next
                End If
                abrand.Enabled = True
                apart.Enabled = True
                aquantity.Enabled = True
                aday.Enabled = True
                amonth.Enabled = True
                ayear.Enabled = True
                add.Enabled = True
                conn.Close()
            Catch ex As Exception
                MsgBox(ex.Message)
            End Try
        End Using
    End Using
End Sub

在 C# 中,使用的语法几乎相同:

// Notice single lined, or multi lined using statements { }
using (var conn = new SqlConnection("server=WIN10;user=admin;password=12345;database=pc_parts"))
  using (var cmd = new SqlCommand())  
  {

  }

幸运的是,在 C#

中没有 With 等价物

使用语法非常相似:

using (conn As new SqlConnection("server=WIN10;user=admin;password=12345;database=pc_parts"))
{
    // some code here
}

我不确定是否有直接的方法来完成您使用 "With" 所做的事情。不过,您可以像这样将赋值内联到对象声明中:

cmd = new SqlCommand {
    Connection = conn,
    CommandType = CommandType.Text,
    CommandText = exist
};
cmd.Parameters.AddWithValue("@build", abuildnumber.Text);