如何将此VB.NET代码转换为C#?

时间:2012-09-29 09:30:27

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

Dim MaxItemID As Integer
Dim objCMD As New SqlCommand(StrSql, objConn)  
MaxItemID = IIf(IsDBNull(objCMD.ExecuteScalar()), 0, objCMD.ExecuteScalar()) + 1

如何在C#中执行此操作?

3 个答案:

答案 0 :(得分:1)

int MaxItemID = 0;
using(SqlCommand objCMD = new SqlCommand(StrSql, objConn))
{
    MaxItemID = (Converter.IsDBNull(objCMD.ExecuteScalar()) ? 0 : objCMD.ExecuteScalar()) + 1;
}

答案 1 :(得分:0)

int MaxItemID;
SqlCommand objCMD =new SqlCommand (StrSql, objConn);
MaxItemID = IsDBNull(objCMD.ExecuteScalar()? 0: objCMD.ExecuteScalar()) + 1;

答案 2 :(得分:0)

这应该这样做(并避免执行SQL两次):

var objCMD = new SqlCommand(StrSql, objConn);
var sqlRes = objCMD.ExecuteScalar();
int maxItemID = 1 + (Convert.IsDBNull(sqlRes) ? 0 : (int)sqlRes);

注意VB会隐式地将object ExecuteScalar的{​​{1}}返回转换为int,但C#不会。