解析布尔值的简单方法?在一行中
本文关键字:一行 布尔值 简单 方法 | 更新日期: 2023-09-27 18:32:56
我正在尝试执行以下操作:
bool? Verified;
Verified = Request.QueryString["verifed"]==null
? null :bool.Parse(Request.QueryString["verifed"]);
但是我收到错误:
无法确定条件表达式的类型,因为
<null>
和bool
之间没有隐式转换
有没有一种简单的单行方法来做到这一点,而不是像这样做:
if (Request.QueryString["confirmed"] == null)
Confirmed = null;
else
Confirmed = bool.Parse(Request.QueryString["confirmed"]);
您收到错误,因为编译器尝试对运算符使用相同的返回类型?:
(即 bool
)。
由于无法将null
转换为bool
,因此可以改为将bool
转换为bool?
:
Verified = Request.QueryString["verifed"] == null ? null :
(bool?)bool.Parse(Request.QueryString["verifed"]);
我认为您的查询参数是空字符串,因此您在转换时会收到此错误。另外为什么要使用可为空的布尔值,只需在值为 null 或 " 时输入 false。
bool initialValue = false;
bool verified = Request.QueryString["verifed"]==null || Request.QueryString["verifed"] == "" ? false:bool.TryParse(Request.QueryString["verifed"], out initialValue);
使用default
关键字;
bool? Verified;
Verified = Request.QueryString["verifed"] == null ? default(bool?) : bool.Parse(Request.QueryString["verifed"]);
如果有人不确定,default(bool?)
的结果是null
的。
需要更多关于这个。读。
"默认"关键字在 C# 中的用法是什么?
什么是默认(对象);用 C# 做?
更改以下内容:
Verified = Request.QueryString["verifed"]==null? null :bool.Parse(Request.QueryString["verifed"]);
对此:
Verified = Request.QueryString["verifed"]==null? (bool?)null :bool.Parse(Request.QueryString["verifed"]);
简单的例子是:
bool test = true;
var test = 1 == 1 ? true : false; // Good
bool? test2 = true;
var test2 = 1 == 1 ? (bool?)null : false; // Good
var test2 = 1 == 1 ? null : false; // Error: Type of conditional expression cannot be determined because there is no implicit conversion between <null> and bool
更多信息:
C#:'
在 C# 中,为什么条件运算符不能隐式转换为可为空的类型