python - .NET 在 Python 中是否有等同于 **kwargs 的东西?

标签 python .net equivalent

我一直无法通过典型的 channel 找到这个问题的答案。

在 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 或类似的东西?

最佳答案

因此,不幸的是,没有办法在 C# 中模拟 Python **kwargs。您将始终在此过程中丢失参数名称(请参阅下面 @alelom 的评论)。

但是,您寻找的似乎是一个可变参数函数。如果你想知道如何用各种编程语言来实现它,最好是看看 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")

关于python - .NET 在 Python 中是否有等同于 **kwargs 的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16201210/

相关文章:

python - 如何从包含类定义的 .py 文件中获取属性名称

c# - 将 .NET GZipStream 类与 Mono 结合使用

objective-c - __VA_ARGS__ 运行时等效?

python - R:与 numpy 的 .dtype.itemsize 和 .dtype.alignment 数组属性等效的 R 是什么?

javascript - 与 document.forms[0].elements[i].value; 等效的 jQuery 是什么?

python - 用 NaN 替换重复的列表元素

Python 2.7 在程序中运行外部 .py 文件

c# - 非零索引数组

python - 索引不匹配时更新 Pandas 数据框的最有效方法

.net - Xamarin 身份验证 - 用户已弃用,迁移到 IAccount 时出现问题