2014-11-22 101 views
1

我已经阅读this an this,但这并不符合我的需求。如何将一对动态的键/值传递给函数?

我学习Csharp的,这里是我的第一个功能之一:

public void AskServer(string URL, WWWForm form) 
{ 
    WWWForm form = new WWWForm(URL); 
    form.AddField("step", StateManager.STEP_GET_CONF); 
    form.AddField("pseudo", this._pseudo); 
    form.AddField("jeton", this._dernierJeton.ToString()); 
    /*... a bit more out of scope code...*/ 
} 

我愿做一个(更)通用这样的东西:

public void AskServer(string URL, ...) 
{ 
    WWWForm form = new WWWForm(URL); 
    /* do a loop on all parameters following the first one */ 
    for (/*dont know how to write this*/) { 
     form.AddField(param[i], param[i+1]); 
    ) 
} 

然后调用函数 - 如何 -

AskServer("http://myweb", "pseudo", this._pseudo, "jeton", this._jeton); 

也许如果你有一个更好的写作方式,欢迎你,也许有些人如在JavaScript中:

AskServer("http://myweb", { 
    "pseudo": this._pseudo, 
    "jeton": this._jeton 
}); 

我的一个问题是,我需要传递的值可能不是字符串(键总是)。

回答

2

的params关键字将让您指定传递尽可能多的参数可变数量的参数(必须是最后一个参数)。然后,您可以将其视为一个数组。

public void AskServer(string url, params object[] args) 
{ 
    WWWForm form = new WWWForm(url); 

    for (int i = 0; i < args.GetLength(0); i++) 
     form.Addfield(args[i].ToString(), args[++i]); 
} 

古称,

AskServer("http://myweb", "pseudo", 1, "jeton", 234); 

或者作为一种替代方法,使用列表,而不是用在关键的强类型(一般声明是丑陋的,所以你可以在命名空间别名吧)

using Kvp = System.Collections.Generic.KeyValuePair<string, object>; 

.... 

public void AskServer(string url, List<Kvp> kvps) 
{ 
    WWWForm form = new WWWForm(url); 

    foreach (var arg in kvps)    
     form.Addfield(arg.Key, arg.Value);    
} 

古称:

AskServer("http://myweb", 
      new List<Kvp>() { 
       new Kvp("pseudo", 1), 
       new Kvp("jeton", 234) 
      }); 
+1

非常感谢您的详细解释,因为我没有说出来,但是这是那种我需要以及件事:详细的解决方案。 – 2014-11-22 16:51:04

0

有几种方法可以获得这个结果。

参数数组,元组,匿名类型,...

例如,你可以写

public void AskServer(string URL, params object[] values) 
{ 
... 
} 

并根据需要

0

我想试试这个...

public void AskServer(string url, KeyValuePair<string, object>[] parameters) 
{ 
    WWWForm form = new WWWForm(URL); 
    /* do a loop on all parameters following the first one */ 
    for (/*dont know how to write this*/) { 
     form.AddField(parameters[i].Key, parameters[i].Value); 
    ) 
} 
相关问题