null-coalescing运算符和操作员&& c#中
-
02-10-2019 - |
题
是否可以一起使用任何方式操作员 ??
和操作员 &&
在下一个情况下:
bool? Any
{
get
{
var any = this.ViewState["any"] as bool?;
return any.HasValue ? any.Value && this.SomeBool : any;
}
}
这意味着接下来:
- 如果
any
那是无效的this.Any.HasValue
返回false
- 如果
any
有价值,然后考虑到另一个布尔属性,它返回价值,即Any && SomeBool
解决方案
我想知道为什么没有人到目前为止建议这样做:
bool? any = this.ViewState["any"] as bool?;
return any & this.SomeBool;
这返回
null
如果any
无效,无论其价值如何this.SomeBool
是;true
如果两者any
和this.SomeBool
是真的;和false
如果any
不是零,this.SomeBool
是错误的。
其他提示
因为你想返回 null
如果来源是 null
, ,我不认为 ??
将帮助您编写任何更短或更清晰的内容。
你是这个意思吗?
bool? Any
{
get
{
return ((this.ViewState["any"] as bool?) ?? false) && this.SomeBool;
}
}
我把回报值留为布尔?但是看起来它可以更改为Bool。
这是这样测试的:
class Program
{
private static readonly Dictionary<string, object> ViewState = new Dictionary<string, object>();
private static bool SomeBool;
static void Main(string[] args)
{
ViewState["any"] = (bool?)null; SomeBool = true; Console.WriteLine(Any);
ViewState["any"] = (bool?)false; SomeBool = true; Console.WriteLine(Any);
ViewState["any"] = (bool?)true; SomeBool = true; Console.WriteLine(Any);
ViewState["any"] = (bool?)null; SomeBool = false; Console.WriteLine(Any);
ViewState["any"] = (bool?)false; SomeBool = false; Console.WriteLine(Any);
ViewState["any"] = (bool?)true; SomeBool = false; Console.WriteLine(Any);
Console.ReadLine();
}
static bool? Any
{
get
{
return ((ViewState["any"] as bool?) ?? false) && SomeBool;
}
}
}
返回
False
False
True
False
False
False
此处的行为与原始AS NULL的行为不完全相同,应归还测试用例1和4的行为。但是也许不需要这种行为?
我认为您要做的是:
return any ?? (any.Value && this.SomeBool) ? true : new Nullable<bool>();
但是,我认为在这样的情况下,使用IF块可能更清楚:
if ( !any.HasValue )
return (any.Value && this.SomeBool) ? true : any;
else
return any;
如果有的话 null
, ,那么你想返回 true
或者 null
, , 对?
无效的合并操作员将无法为您如何为方法构建逻辑。当然,您可以将其强加于那里,但是它看起来很丑陋,只是让任何阅读的人感到困惑。
我发现原始代码难以阅读和理解,因此被重构并删除了三元操作员以揭示意图。
bool? any = this.ViewState["any"] as bool?;
if (any == null)
return null;
return any.Value && this.SomeBool;
无效合并只是不错的速记,应明智地使用
Person contact = Mother ?? Father ?? FirstSibling;
比以下方式更容易揭示,并且更易于阅读 +维护:
Person contact = Mother;
if (contact == null)
contact = Father;
if (contact == null)
contact = FirstSibling;
事实是,您真的不想使用?操作员。它的意思是使避免空,您实际上要保持零。
这具有您描述的行为:
return (any ?? false) && this.SomeBool
不隶属于 StackOverflow