我以前在 VB.NET 中有一个代码,它在 DB 中搜索一个值并为我提供了一个结果。这是代码:
Class UserData
Dim theResults = New List(Of UserData)
Property Name As String
Property LastName As String
End Class
Function GetData(ByVal clientNo As Integer) As List(Of UserData)
Dim theResults = New List(Of UserData)
Dim connStr = "serverstring"
Using conn = New SqlConnection(connStr)
Dim sql = "SELECT [Name], [PaternalLastName], [MaternalLastName] FROM [SocioInfo] Where ([SocioNum] = @SocioNum)"
Dim sqlCmd = New SqlCommand(sql, conn)
sqlCmd.Parameters.AddWithValue("@SocioNum", CStr(txtInput.Text))
conn.Open()
Dim rdr = sqlCmd.ExecuteReader
While rdr.Read
theResults.Add(New UserData With {
.Name = rdr.GetString(0),
.LastName = rdr.GetString(1),
.Maternal = rdr.GetString(2)
})
End While
conn.Close()
End Using
Return theResults
End Function
Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click
Dim clientNo As Integer = 0
Dim myResults = GetData(clientNo)
If Integer.TryParse(txtInput.Text, clientNo) Then
If myResults.Count = 1 Then
Execute Code
Else
MessageBox.Show("NAH")
End If
Else
MessageBox.Show("NAH")
End If
End Sub
现在我尝试将此代码转换为 C#,但失败得很惨。我使用了一些我在网上找到的转换器,但它抛出了异常,所以我尝试手动操作,但我不知道代码或正确的方法,因为我仍在学习 C# 中的技巧。如果有人可以提供帮助,将不胜感激:)
C#代码:
{
theResults = new List<UserData>();
public string Nombre { get; set; }
public string Apellido { get; set; }
public string ApellidoMaterno { get; set; }
}
public List<UserData> GetData(int clientNo)
{
dynamic theResults = new List<UserData>();
dynamic connStr = "Data Source=lsf-corapbk-01;Initial Catalog=Custmast_CO;Integrated Security=Yes";
using (conn == new SqlConnection(connStr))
{
dynamic sql = "SELECT [Name], [PaternalLastName], [MaternalLastName] FROM [SocioInfo] Where ([SocioNum] = @SocioNum)";
dynamic sqlCmd = new SqlCommand(sql, conn);
sqlCmd.Parameters.AddWithValue("@SocioNum", Convert.ToString(txtInput.Text));
conn.Open();
dynamic rdr = sqlCmd.ExecuteReader;
while (rdr.Read)
{
theResults.Add(new UserData
{
Nombre = rdr.GetString(0),
Apellido = rdr.GetString(1),
ApellidoMaterno = rdr.GetString(2)
});
}
conn.Close();
}
return theResults;
}
大多数例外都在 UserData 区域中。