Does .NET have an equivalent of **kwargs in Python?

孤街醉人 提交于 2019-12-10 20:45:54

问题


I haven't been able to find the answer to this question through the typical channels.

In Python I could have the following function definition

def do_the_needful(**kwargs):
    # Kwargs is now a dictionary
    # i.e. do_the_needful(spam=42, snake='like eggs', spanish='inquisition')
    # would produce {'spam': 42, 'snake': 'like eggs', 'spanish': 'inquisition' }

I know .NET has the ParamArray, which produces a sequence of unnamed arguments, similar to the *args syntax in Python... Does .NET have an equivalent of **kwargs, or something similar?


回答1:


What you look for is called a variadic function. If you want to know how to implement it in various programming languages, the best is to look at the Wikipedia page about it.

So, according to the Wikipedia, implementing a variadic function in C# and VisualBasic is done like this:

Other languages, such as C#, VB.net, and Java use a different approach—they just allow a variable number of arguments of the same (super)type to be passed to a variadic function. Inside the method they are simply collected in an array.

C# Example

public static void PrintSpaced(params Object[] objects)
{
    foreach (Object o in objects)
        Console.Write(o + " "); 
}    
// Can be used to print: PrintSpaced(1, 2, "three");

VB.Net example

Public Shared Sub PrintSpaced(ParamArray objects As Object())
    For Each o As Object In objects
        Console.Write(o & " ")
    Next
End Sub

' Can be used to print: PrintSpaced(1, 2, "three")



来源:https://stackoverflow.com/questions/16201210/does-net-have-an-equivalent-of-kwargs-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!