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

时间:2017-11-30 15:11:05

标签: c# .net vb.net vb.net-to-c#

所以我试着学习c#,因为我想改变我的旧编程技巧,即vb.net我打开一些转换器网站,但它不起作用。我只是想知道在vb.net中使用和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

2 个答案:

答案 0 :(得分:3)

在C#中,using的语法基本相同:

// 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等价物

答案 1 :(得分:2)

使用语法非常相似:

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