[英]Convert list to params C#
I have this following list: 我有以下列表:
var myList = new List<KeyValuePair<string, object>>();
And this function: 而这个功能:
public void Test(params KeyValuePair<string, object>[] list)
How can I do a conversion of the list to params when using the function? 使用该功能时,如何将列表转换为参数? Like that:
像那样:
Test(myList);
您方法声明KeyValuePair<string, object>[] list
声明它将接受一个数组,因此您需要将列表转换为数组,如下所示
Test(myList.ToArray());
You should convert the list to form which is accepted as parameter. 您应该将列表转换为接受为参数的表单。 In this case convert List to Array
在这种情况下,将List转换为Array
Hence, 因此,
var arrayParam = mylist.ToArray();
Test(arrayParam);
Given the original question, I think it's worth clarifying how the params
keyword functions. 鉴于原始问题,我认为值得澄清
params
关键字的功能。 It has to be a decorator on a 1D array, and simply allows an alternate syntax for calling the function. 它必须是1D数组的装饰器,并且只允许使用替代语法来调用该函数。
For example if we have a string concatenation function: 例如,如果我们有一个字符串连接函数:
public string Test(string[] names) {
return String.Join(",", names);
}
This can be called using 这可以使用
Test(new[] { "Fred", "Wilma", "Pebbles"});
but the inclusion of the params
keyword simply allows a friendlier looking calling syntax: 但是包含
params
关键字只是允许更友好的查看调用语法:
public string Test(params string[] names) {
return String.Join(",", names);
}
Test("Fred", "Wilma", "Pebbles");
I'm not a huge fan of the params
keyword, but I do sometimes use it to make calling code more readable (as in this example). 我不是
params
关键字的忠实粉丝,但我确实使用它来使调用代码更具可读性(如本例所示)。
So when the OP asks " How can I do a conversion of the list to params? ", the underlying truth is that you don't, as params is not a type and is simply a "syntactical sugar" feature to give an alternative syntax for passing in an array. 因此,当OP询问“ 如何将列表转换为params? ”时,根本的事实是你没有,因为params不是一种类型,只是一种“语法糖”功能来提供替代语法用于传入数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.