如何简化 C# 中可空布尔值的使用
下面是一些入门示例代码:
class Foo
{
public bool? IsValid { get; set; }
}
// later in some other function...
void DoStuff( Foo myFoo )
{
myControlState.Visible = myFoo.IsValid.HasValue ? myFoo.IsValid.Value : false;
}
我遇到了很多情况,必须使用上面这样的三元运算符才能正确使用可为 null 的布尔值。如果有一种稍微简单的方法来获取 bool 的值而不抛出异常,那就太好了。上面的代码看起来很简单,但在更复杂的情况下,最终会产生大量代码。我希望得到一些简单的东西,比如:
myControlState.Visible = GetNullableValue<bool>( myFoo );
有没有人有比三元运算符更干净的替代方案?
Here is some example code to get started:
class Foo
{
public bool? IsValid { get; set; }
}
// later in some other function...
void DoStuff( Foo myFoo )
{
myControlState.Visible = myFoo.IsValid.HasValue ? myFoo.IsValid.Value : false;
}
I run into a lot of situations where I have to use a ternary operator like above to properly use a nullable bool. It would be nice if there was a slightly simpler way of getting the value of the bool without throwing exceptions. The code above seems straight-forward but there are much more complex situations where this ends up being a lot of code. I was hoping for something simple like:
myControlState.Visible = GetNullableValue<bool>( myFoo );
Does anyone have any cleaner alternatives to the ternary operator?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用空合并运算符(如果这使其更具可读性)。
you can use the null-coalescing operator if that makes it more readable.
这个更优雅
This is more elegant
如果您正在从 SQL Server 读取位值并希望检查空错误,请
在从 SQL Server 读取数据时对数据行使用以下扩展方法。
If you are reading bit values from the SQL server and want to check against null errors, Use the following Extension method against the data Row
and when you are reading data from the SQL server put in.