Key value pairs in C# Params

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

    A bit of a hack, but you could have your Message class implement the IEnumerable interface and give it an Add method. You'll then be able to use collection initializer syntax:

    Agent.SendMessage
    (
        new Message(MessageTypes.SomethingHappened) {{ "foo", 42 }, { "bar", 123 }}
    );
    
    // ...
    
    public class Message : IEnumerable
    {
        private Dictionary _map = new Dictionary();
    
        public Message(MessageTypes mt)
        {
            // ...
        }
    
        public void Add(string key, object value)
        {
            _map.Add(key, value);
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return ((IEnumerable)_map).GetEnumerator();
            // or throw a NotImplementedException if you prefer
        }
    }
    

提交回复
热议问题