我一直无法通过典型的 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/