c# multi assignment

后端 未结 7 1794
温柔的废话
温柔的废话 2020-12-16 13:54
int a, b, n;
...
(a, b) = (2, 3);
// \'a\' is now 2 and \'b\' is now 3

This sort of thing would be really helpfull in C#. In this example \'a\' and

7条回答
  •  庸人自扰
    2020-12-16 14:07

    As others already wrote, C# 4 Tuples are a nice addition, but nothing really compelling to use as long as there aren't any unpacking mechanisms. What I really demand of any type I use is clarity of what it describes, on both sides of the function protocol (e.g. caller, calle sides)... like

    Complex SolvePQ(double p, double q)
    {
        ...
        return new Complex(real, imag);
    }
    ...
    var solution = SolvePQ(...);
    Console.WriteLine("{0} + {1}i", solution.Real, solution.Imaginary);
    

    This is obvious and clear at both caller and callee side. However this

    Tuple SolvePQ(double p, double q)
    {
        ...
        return Tuple.Create(real, imag);
    }
    ...
    var solution = SolvePQ(...);
    Console.WriteLine("{0} + {1}i", solution.Item1, solution.Item2);
    

    Doesn't leave the slightest clue about what that solution actually is (ok, the string and the method name make it pretty obvious) at the call site. Item1 and Item2 are of the same type, which renders tooltips useless. The only way to know for certain is to "reverse engineer" your way back through SolvePQ.

    Obivously, this is far fetched and everyone doing serious numerical stuff should have a Complex type (like that in the BCL). But everytime you get split results and you want give those results distinct names for the sake of readability, you need tuple unpacking. The rewritten last two lines would be:

    var (real, imaginary) = SolvePQ(...); // or var real, imaginary = SolvePQ(...);
    Console.WriteLine("{0} + {1}i", real, imaginary);
    

    This leaves no room for confusion, except for getting used to the syntax.

提交回复
热议问题