Key value pairs in C# Params

前端 未结 8 2448
后悔当初
后悔当初 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

    With dynamic type in C# 4.0:

    public class MyClass
    {
        // Could use another generic type if preferred
        private readonly Dictionary _dictionary = new Dictionary();
    
        public void MyFunction(params dynamic[] kvps)
        {
            foreach (dynamic kvp in kvps)
                _dictionary.Add(kvp.Key, kvp.Value);
        }
    }
    

    Call using:

    MyFunction(new {Key = "Key1", Value = "Value1"}, new {Key = "Key2", Value = "Value2"});
    

提交回复
热议问题