Key value pairs in C# Params

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

    Funny, I just created (minutes ago) a method that allows to do that, using anonymous types and reflection :

    MyMethod(new { Key1 = "value1", Key2 = "value2" });
    
    
    public void MyMethod(object keyValuePairs)
    {
        var dic = DictionaryFromAnonymousObject(keyValuePairs);
        // Do something with the dictionary
    }
    
    public static IDictionary<string, string> DictionaryFromAnonymousObject(object o)
    {
        IDictionary<string, string> dic = new Dictionary<string, string>();
        var properties = o.GetType().GetProperties();
        foreach (PropertyInfo prop in properties)
        {
            dic.Add(prop.Name, prop.GetValue(o, null) as string);
        }
        return dic;
    }
    
    0 讨论(0)
  • 2021-02-11 15:42

    Using a dictionary:

    myFunction(new Dictionary<string, object>(){
      {"Key", value}, 
      {"Key2", value}});
    

    Which is straight forward, you need only one new Dictionary<K, V>, not for each argument. It's trivial to get the keys and values.

    Or with an anonymous type:

    myFunction(new {
      Key = value, 
      Key2 = value});
    

    Which is not very nice to use inside the function, you'll need reflection. This would look something like this:

    foreach (PropertyInfo property in arg.GetType().GetProperties())
    {
      key = property.Name;
      value = property.GetValue(arg, null);
    }
    

    (Staight from my head, probably some errors...)

    0 讨论(0)
提交回复
热议问题