C# 无法使用三元运算符确定条件表达式错误
三值运算符C# 无法使用三元运算符确定条件表达式错误,c#,.net,C#,.net,三值运算符出现以下错误 错误:无法确定条件表达式的类型,因为“”和“int”之间没有隐式转换 为什么即使我已为ExecuteScalar结果指定了(int)(result),仍会出现此错误?我们怎样才能纠正它 代码 public int? GetWINFromAssociateID(int associateID) { int? WIN =null; using (SqlConnection connection = new SqlConnecti
出现以下错误
错误:无法确定条件表达式的类型,因为“”和“int”之间没有隐式转换
为什么即使我已为ExecuteScalar
结果指定了(int)(result)
,仍会出现此错误?我们怎样才能纠正它
代码
public int? GetWINFromAssociateID(int associateID)
{
int? WIN =null;
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
string commandText = DataLayerConstants.GetWINFromAssociateIDCommand;
using (SqlCommand command = new SqlCommand(commandText, connection))
{
command.CommandType = System.Data.CommandType.Text;
command.Parameters.AddWithValue("@payroll_svc_assoc_id", associateID);
var result = command.ExecuteScalar();
WIN = result == DBNull.Value ? null : (int)(result);
}
}
return WIN;
}
更新的参考资料
您应该将三元运算符中的null强制转换为int?:
Win=result==DBNull.Value?(int?)null:(int?)result;
您应该将三元运算符中的null强制转换为int?:
Win=result==DBNull.Value?(int?)null:(int?)result;
这是因为有命令。ExecuteScalar
返回对象
类型的实例;您可能没有返回整数
您需要使用int.Parse
或更好的int.TryParse
int.Parse(result.ToString());
或
这是因为有命令。ExecuteScalar
返回对象
类型的实例;您可能没有返回整数
您需要使用int.Parse
或更好的int.TryParse
int.Parse(result.ToString());
或
不必同时强制转换null和result;任意一个都可以。在这种情况下,这是必要的,因为结果有类型object。好的,我读得太匆忙了;我的评论只对了一半。我应该写“不必同时强制转换null
和result
;强制转换result
就足够了”(因为有一个从null到int的隐式转换?
)。不必同时强制转换null和result;任意一个都可以。在这种情况下,这是必要的,因为结果有类型object。好的,我读得太匆忙了;我的评论只对了一半。我应该写“不必同时使用null
和result
;使用result
就足够了”(因为有一个从null到int的隐式转换?
)。阅读这个答案和你会在那里找到的链接:阅读这个答案和你会在那里找到的链接: