如何在C#中将数据库对象转换为int?

net*_*ner 3 c# database type-conversion

如何在C#中将数据库对象转换为int?

int uid = Convert.ToInt32(dt.Rows[0]["userid"].ToString());
Run Code Online (Sandbox Code Playgroud)

Bri*_*ott 6

在转换为int之前,不应将对象转换为字符串.

int uid = Convert.ToInt32(dt.Rows[0]["userid"]);
Run Code Online (Sandbox Code Playgroud)

如果需要将字符串转换为int,则使用;

int uid = int.Parse("1");
Run Code Online (Sandbox Code Playgroud)


var*_*jan 5

在转换为整数之前使用Null Check.

DataRow row=dt.Rows[0];
int uid = row.IsNull("userid") ? 0 : (Convert.ToInt32(dt.Rows[0]["userid"]); 
Run Code Online (Sandbox Code Playgroud)