【问题标题】:Expression is always true Resharper Hint表达式总是正确的 Resharper 提示
【发布时间】:2018-07-24 12:08:20
【问题描述】:

编辑:感谢您的回答,那么应该如何写才能清楚地在每一行中说明条件是什么,或者为了可读性而保持原样? p>

我从How do I concatenate two arrays in C#? 中采用了answer 来返回一个空数组而不是抛出错误

public static T[] Concat<T>(this T[] x, T[] y)
{
    
    if (x == null && y != null) return  y;
    if (x != null && y == null) return  x;
    if (x == null && y == null) return new T[0];

    int oldLen = x.Length;
    Array.Resize<T>(ref x, x.Length + y.Length);
    Array.Copy(y, 0, x, oldLen, y.Length);
    return x;
}

Resharper 正在制作波浪线,“表达式始终为真”提示:

我不明白的是 2 个不同的变量应该有 4 个不同的情况,每个 2 个,4 的排列:(x 为空,x 不为空)(y 为空,y 不为空)

所以我试图在 if 中捕获 4 个案例

更改行的顺序只是将波浪线移动到最后一个 if 行。

【问题讨论】:

  • 您的第一个条件符合y == null
  • 您的编辑现在更像是一个基于意见的问题。我个人更喜欢@MichaelRandall 的答案中的两行版本,其次是我的答案中的三行版本。但如果你更喜欢你写的那个,那就用那个吧!最后不会有什么不同。什么被认为是“可读的”部分取决于你阅读代码的时间。我仍然不能总是第一次阅读 Linq Zip 语句。 :)
  • @RufusL :我刚刚明白我需要什么,Michael Randall 的代码就是我想要的,谢谢!

标签: c# optimization resharper


【解决方案1】:
if (x == null && y != null) return  y;
if (x != null && y == null) return  x;
if (x == null && y == null) return new T[0];

1 如果 x 为空且 y 不为空,则返回 y

2 如果 x 不为空且 y 为空,则返回 x

3 如果 x 为空,那么根据您的第一个条件,y 必须为空。

【讨论】:

    【解决方案2】:

    布尔代数命题逻辑恶作剧

    当你写这篇文章时

    if (x == null && y != null) return  y;
    

    那么当你再次比较x == null,那么y == null天生就是真的

    不可能是别的

    更新

    if (x == null) return y ?? new T[0];
    if (y == null) return x;
    ...
    
    int oldLen = x.Length;
    Array.Resize<T>(ref x, x.Length + y.Length);
    Array.Copy(y, 0, x, oldLen, y.Length);
    return x;
    

    就这么简单

    【讨论】:

    • 一个问题,如果它们都为空怎么办?我需要发送一个新的空数组。
    【解决方案3】:

    如果我们查看您的第一张和最后一张支票:

    if (x == null && y != null) return  y;
    if (x == null && y == null) return new T[0];
    

    请注意,我们已经测试了x == null &amp;&amp; y != null,所以如果我们通过了检查,那么我们肯定知道如果x == null y 有 为 null(如果不是,那么我们已经返回了 y

    这是一种无需冗余检查即可检查相同条件的方法:

    if (x == null && y == null) return new T[0];   // If they're both null, return a new thing
    if (x == null) return y;                       // Otherwise if only one of them is null,
    if (y == null) return x;                       // then return the other one
    

    或者,如果这是你的事,你可以在一行中完成所有操作:

    if (x == null || y == null) return x == null ? y == null ? new T[0] : y : x;
    

    【讨论】:

      猜你喜欢
      • 2011-07-30
      • 2011-07-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      • 2015-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多