在Python中.NET是否有一个等价的**kwargs?

2024-09-30 14:18:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我还没能通过典型的渠道找到这个问题的答案。在

在Python中,我可以有以下函数定义

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' }

我知道.NET有ParamArray,它产生一系列未命名的参数,类似于Python中的*args语法。。。.NET是否有**kwargs的等价物,或者类似的东西?在


Tags: the函数答案netspamdoeggskwargs
1条回答
网友
1楼 · 发布于 2024-09-30 14:18:24

你要找的是一个变量函数。如果您想知道如何用不同的编程语言实现它,最好的方法是看看关于它的Wikipedia page。在

因此,根据维基百科的说法,在C和VisualBasic中实现一个可变函数是这样完成的:

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")

相关问题 更多 >