你是这个意思吗?
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
此处的行为与原始行为不完全相同,因为测试用例 1 和 4 应返回 null 以使其相同。但也许这种行为不是必需的?