Key value pairs in C# Params

前端 未结 2 1791
[愿得一人]
[愿得一人] 2021-02-11 14:53

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

2条回答
  •  无人及你
    2021-02-11 15:29

    When the syntax is bad for an otherwise decent pattern, change the syntax. How about:

    public void MyFunction(params KeyValuePair[] pairs)
    {
        // ...
    }
    
    public static class Pairing
    {
        public static KeyValuePair Of(string key, object value)
        {
            return new KeyValuePair(key, value);
        }
    }
    

    Usage:

    MyFunction(Pairing.Of("Key1", 5), Pairing.Of("Key2", someObject));
    

    Even more interesting would be to add an extension method to string to make it pairable:

    public static KeyValuePair PairedWith(this string key, object value)
    {
        return new KeyValuePair(key, value);
    }
    

    Usage:

    MyFunction("Key1".PairedWith(5), "Key2".PairedWith(someObject));
    

    Edit: You can also use the dictionary syntax without the generic brackets by deriving from Dictionary<,>:

    public void MyFunction(MessageArgs args)
    {
        // ...
    }
    
    public class MessageArgs : Dictionary
    {}
    

    Usage:

    MyFunction(new MessageArgs { { "Key1", 5 }, { "Key2", someObject } });
    

提交回复
热议问题