代码检查:替换为单一赋值
要根据某个条件为 bool 变量设置值,您可以使用一个语句,将条件检查和赋值合并在一起。
如下所示, 包含 方法的结果决定了 布尔型 a 是 true 还是 false。 包含 返回 bool,因此您可以将方法的结果直接赋值给 a。 JetBrains Rider 帮助您消除 If 语句,并将 包含 的结果赋值给 a。
private static void TestConvertIf(string s)
{
bool a = true;
if (s.Contains("."))
{
a = false;
}
Console.WriteLine(a);
}
private static void TestConvertIf(string s)
{
bool a = !s.Contains(".");
Console.WriteLine(a);
}
最后修改日期: 2025年 9月 26日