×

Loading...

Topic

This topic has been archived. It cannot be replied.
  • 工作学习 / 学科技术 / how to swap two values in .net? for example int a, int b, how to swap the value of them?

    老方法是借助一个临时变量 c

    C# 7以后引入了一个新的语法

    (a,b) = (b,a);

    ya easy..

    • Any use cases of switching values of two variables?
      • 好问题,吃饱了撑的😂而且不管你表面怎么简化,机器内部还是要通过第三个变量去做,整数之类的小东西没啥,物体数列之类的大东西最好写在面上,省得被忽略。
        • I don't remember that I ever needed to do such switching.
          • 前面写错了,后面想改回去? 😂
      • 刷题时天天 swap two variables lol
      • 很常见啊。比如quicksort里就需要用到
        • theArray.sort()😆
          • Quick select也需要:找出第n大的数。
    • 如果加减不溢出,可以不需要临时变量:

      a += b

      b = a - b

      a -= b

      • 不好。不易懂,难维护。主贴的意思是将来的编程应该这样: swap(a,b)
      • a,b的type不一定是int,可以是任意 T a, T b, (a,b)=(b,a) 是 Tuple<>的一个语法糖
        • 在 js 里通过 destructuring expression,看上去很类似,不过 js array destructuring 超实用... 个人觉得 c# / es6+ 是最简练,最优雅的... 不过c#最近的版本有一些 features 有点为语法糖而语法糖了...
          The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.