orC#中是否有运营商?
我想要做:
if (ActionsLogWriter.Close or ErrorDumpWriter.Close == true)
{
// Do stuff here
}
Run Code Online (Sandbox Code Playgroud)
但我不知道我怎么能这样做.
Jef*_*nal 80
C#支持两个布尔or运算符:单个条|和双条||.
区别在于|始终检查左右条件,而||只检查右侧条件是否有必要(如果左侧评估为假).
当右侧的病症涉及处理或导致副作用时,这是很重要的.(例如,如果您的ErrorDumpWriter.Close方法需要一段时间才能完成或更改某些状态.)
Noa*_*ahl 18
从 C# 9 开始,有一个or关键字可用于匹配“析取模式”。这是此版本中几个新的模式匹配增强功能的一部分。
文档中的一个示例:
public static bool IsLetter(this char c) => c is >= 'a' and <= 'z' or >= 'A' and <= 'Z';
Run Code Online (Sandbox Code Playgroud)
另外值得一提的是,在C#中OR运算符是短路的.在您的示例中,Close似乎是一个属性,但如果它是一个方法,则值得注意:
if (ActionsLogWriter.Close() || ErrorDumpWriter.Close())
Run Code Online (Sandbox Code Playgroud)
从根本上说是不同的
if (ErrorDumpWriter.Close() || ActionsLogWriter.Close())
Run Code Online (Sandbox Code Playgroud)
在C#中,如果第一个表达式返回true,则根本不会计算第二个表达式.请注意这一点.它在大多数情况下实际上对你有利.