int 和字符串之间没有隐式转换

本文关键字:转换 字符串 之间 int | 更新日期: 2023-09-27 18:30:33

当我尝试执行这个贝洛代码时,我遇到了错误。

//法典:

 int Value = Convert.ToInt32(Request.QueryString["Value"] == null ? 0 : Request.QueryString["Value"]);

因此,如果QueryString值为空,我需要传递值"0"。

我该如何解决这个问题?

int 和字符串之间没有隐式转换

int Value = Convert.ToInt32(Request.QueryString["Value"] ?? "0");

你可以"0"传递字符串,但更好的方法是:

int Value = Request.QueryString["Value"] == null ? 0 : Convert.ToInt32(Request.QueryString["Value"]);

您还可以分解查找:

string str = Request.QueryString["Value"];
int value = str == null ? 0 : Convert.ToInt32(str);

试试这个

int Value = Convert.ToInt32(Request.QueryString["Value"] == null ? "0" : Request.QueryString["Value"]);

或者利用??操作员的优势

int Value = Convert.ToInt32(Request.QueryString["Value"] ?? "0");

您在三元运算符中的假陈述和真陈述应该是同一类型,或者应该隐式转换为另一个。

first_expression和second_expression的类型必须相同,或者必须存在从一种类型到另一种类型的隐式转换。

取自 msdn

试试这个:

int i;
int.TryParse(Request.QueryString["Value"], out i);

如果解析失败i将具有默认值 (0),而无需显式分配并检查查询字符串是否为 null。