无法将C#字典作为参数传递给ironPython方法
我需要将字典中存储的参数列表传递给函数 由ironPython类实现 我准备了再现错误的最小示例:无法将C#字典作为参数传递给ironPython方法,c#,python,dictionary,parameters,ironpython,C#,Python,Dictionary,Parameters,Ironpython,我需要将字典中存储的参数列表传递给函数 由ironPython类实现 我准备了再现错误的最小示例: // C# Side var runtime = Python.CreateRuntime(); dynamic test = runtime.UseFile("test.py"); // Here the parameters dictionary is instantiated and filled var pa
// C# Side
var runtime = Python.CreateRuntime();
dynamic test = runtime.UseFile("test.py");
// Here the parameters dictionary is instantiated and filled
var parametersDictionary = new Dictionary<string, int>();
parametersDictionary.Add("first", 1);
// The Python 'x' instance is called passing parameter dictionary
var result = test.x.ReturnFirstParameter(parametersDictionary);
当我运行该程序时,会出现以下异常:
ReturnFirstParameter() takes exactly 1 argument (2 given)
第一个参数是“self”,但似乎忽略了它
2个参数,“self”和字典
我尝试过为其他参数更改字典,效果很好。问题
仅当您收到**参数时才会出现
我非常感谢你的帮助
Esteban。在Python代码中,只需从
参数前面删除**
,即可:
# Python side
# Class 'Expression' definition
class Expression(object):
def ReturnFirstParameter(self, **parameters):
return parameters['first']
# Class 'Expression' instantiation
x = Expression()
class Expression(object):
def ReturnFirstParameter(self, parameters):
return parameters['first']
当您将命名参数传递给函数时,应使用**
,而您的C#代码将传递字典
您的C#代码将调用如下函数:
x.ReturnFirstParameter({'first': 1})
要使其使用**参数
,调用需要
x.ReturnFirstParameter(first=1)
ironpython可能有办法做到这一点,但我不确定如何做到。这个**
是一种特殊的Python语法(将所有关键字参数收集到一个dict中),我不知道您是否可以从C#使用它。你为什么需要它?谢谢你,它成功了!我猜类字典是在IronPhyton框架内定义的,并作为引用接收的。我认为它将C#字典转换为**python类型,但事实并非如此。谢谢@user1275011-很高兴它有帮助!