Key value pairs in C# Params

前端 未结 8 2420
后悔当初
后悔当初 2021-02-11 14:55

I\'m looking for a way to have a function such as:

myFunction({\"Key\", value}, {\"Key2\", value});

I\'m sure there\'s something with anonymous

8条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-11 15:34

    Since C# 7.0, you can use value tuples. C# 7.0 not only introduces a new type but a simplified syntax for tuple types and for tuple values. A tuple type is simply written as a list of types surrounded by braces:

    (string, int, double)
    

    The corresponding elements are named Item1, Item2, Item2. You can also specify optional aliases. These aliases are only syntactic sugar (a trick of the C# compiler); the tuples are still based on the invariant (but generic) System.ValueTuple struct.

    (string name, int count, double magnitude)
    

    Tuple values have a similar syntax, except that you specify expressions instead of types

    ("test", 7, x + 5.91)
    

    or with the aliases

    (name: "test", count: 7, magnitude: x + 5.91)
    

    Example with params array:

    public static void MyFunction(params (string Key, object Value)[] pairs)
    {
        foreach (var pair in pairs) {
            Console.WriteLine($"{pair.Key} = {pair.Value}");
        }
    }
    

    It is also possible to deconstruct a tuple like this

    var (key, value) = pair;
    Console.WriteLine($"{key} = {value}");
    

    This extracts the items of the tuple in two separate variables key and value.

    Now, you can call MyFunction with a varying number of arguments easily:

    MyFunction(("a", 1), ("b", 2), ("c", 3));

    It allows us to do things like

    DrawLine((0, 0), (10, 0), (10, 10), (0, 10), (0, 0));
    

    See: New Features in C# 7.0

提交回复
热议问题