Tag: 短路

我不喜欢这个……这是欺骗语言吗?

我已经看过几次以下的东西……而且我讨厌它。 这基本上是“欺骗”语言吗? 或者..你会认为这是’ok’,因为IsNullOrEmpty会一直被评估吗? (我们可以争论一个字符串在出现函数时是否应该为NULL,但这不是问题。) string someString; someString = MagicFunction(); if (!string.IsNullOrEmpty(someString) && someString.Length > 3) { // normal string, do whatever } else { // On a NULL string, it drops to here, because first evaluation of IsNullOrEmpty fails // However, the Length function, if used by itself, would throw an exception. } 编辑:再次感谢大家提醒我这种语言的基础。 虽然我知道“为什么”它起作用,但我无法相信我不知道/记住这个概念的名称。 […]

我可以在方法调用中强制自己进行短路吗?

假设我想检查一堆对象以确保none为null: if (obj != null && obj.Parameters != null && obj.Parameters.UserSettings != null) { // do something with obj.Parameters.UserSettings } 编写一个辅助函数来接受可变数量的参数并简化这种检查是一个诱人的前景: static bool NoNulls(params object[] objects) { for (int i = 0; i < objects.Length; i++) if (objects[i] == null) return false; return true; } 然后上面的代码可能变成: if (NoNulls(obj, obj.Parameters, obj.Parameters.UserSettings)) { // do something } […]

为什么短路不能阻止与逻辑AND(&&)的不可达分支相关的MissingMethodException?

在检查我的Windows移动设备上是否有相机并启用时,我遇到了一些我不明白的事情。 代码如下所示: public static bool CameraP(){ return Microsoft.WindowsMobile.Status.SystemState.CameraPresent; } public static bool CameraE() { return Microsoft.WindowsMobile.Status.SystemState.CameraEnabled; } public static bool CameraPresent1() { return Microsoft.WindowsMobile.Status.SystemState.CameraPresent && Microsoft.WindowsMobile.Status.SystemState.CameraEnabled; } public static bool CameraPresent2() { return CameraP() && CameraE(); } 当我调用CameraPresent2()它返回false(没有相机存在)。 但是,当我调用CameraPresent1()我收到一条MissingMethodException并注释“找不到方法:get_CameraEnabled Microsoft.WindowsMo​​bile.Status.SystemState。” 在CameraPresent1评估第二个术语是因为它们都是属性(在语言级别)? 还有什么能解释行为上的差异吗?

C#If语句中条件的执行顺序

下面有两个if语句,它们使用逻辑运算符有多个条件。 逻辑上两者都相同,但检查顺序不同。 第一个工作,第二个工作失败。 我引用了MSDN来检查是否定义了执行条件的顺序; 但我找不到。 考虑具有&&作为逻辑运算符的多重检查条件。 是否保证始终检查第一个条件,如果不满足,则不会检查第二个条件? 我曾经使用方法1,它运作良好。 寻找certificate其使用的MSDN参考资料。 UPDATE 参考“短路”评估 码 List employees = null; if (employees != null && employees.Count > 0) { string theEmployee = employees[0]; } if (employees.Count > 0 && employees != null) { string theEmployee = employees[0]; }

短路声明评估 – 这有保证吗?

这里有关于C#中的短路语句的快速问题。 使用if语句: if (MyObject.MyArray.Count == 0 || MyObject.MyArray[0].SomeValue == 0) { //…. } 是否保证评估将在“MyArray.Count”部分后停止,前提是该部分为真? 否则我会在第二部分得到一个nullexception。

C#中的| =和&=赋值运算符短路

我知道|| 和&&被定义为C#中的短路运算符,这种行为是由语言规范保证的,但是也做|=和&=短路? 例如: private bool IsEven(int n) { return n % 2 == 0; } private void Main() { var numbers = new int[] { 2, 4, 6, 8, 9, 10, 14, 16, 17, 18, 20 }; bool allEven = true; bool anyOdd = false; for (int i = 0; i < numbers.Length; i++) { […]