问题描述
我正在使用加载C#程序集以调用C#代码从Python。这很干净,但是我遇到了一个调用如下所示方法的问题:
I'm using Python.NET to load a C# Assembly to call C# code from Python. This works pretty cleanly, however I am having an issue calling a method that looks like this:
Our.Namespace.Proj.MyRepo中的方法:
A method within Our.Namespace.Proj.MyRepo:
OutputObject GetData(string user, int anID, int? anOptionalID= null)
在存在可选的第三个参数的情况下,我可以调用此方法,但无法弄清楚第三个参数要传递什么以匹配空值。
I can call the method for the case where the optional third argument is present but can't figure out what to pass for the third argument to match the null case.
import clr
clr.AddReference("Our.Namespace.Proj")
import System
from Our.Namespace.Proj import MyRepo
_repo = MyRepo()
_repo.GetData('me', System.Int32(1), System.Int32(2)) # works!
_repo.GetData('me', System.Int32(1)) # fails! TypeError: No method matches given arguments
_repo.GetData('me', System.Int32(1), None) # fails! TypeError: No method matches given arguments
iPython Notebook指示最后一个参数应为类型:
The iPython Notebook indicates that the last argument should be of type:
System.Nullable`1[System.Int32]
只是不确定如何创建与Null大小写匹配的对象。
Just not sure how to create an object that will match the Null case.
关于如何创建C#的任何建议识别空对象?我认为传递原生Python None不会起作用,但不会。
Any suggestions on how to create a C# recognized Null object? I assumed passing the native Python None would work, but it does not.
推荐答案
这已合并到pythonnet:
This has been merged to pythonnet:
我遇到了可空基元的同一问题-在我看来,Python.NET不支持这些类型。我通过在Python.Runtime.Converter.ToManagedValue()(\src\runtime\converter.cs)中添加以下代码来解决此问题:
I ran into the same issue with nullable primitives -- it seems to me that Python.NET doesn't support these types. I got around the problem by adding the following code in Python.Runtime.Converter.ToManagedValue() (\src\runtime\converter.cs)
if( obType.IsGenericType && obType.GetGenericTypeDefinition() == typeof(Nullable<>) )
{
if( value == Runtime.PyNone )
{
result = null;
return true;
}
// Set type to underlying type
obType = obType.GetGenericArguments()[0];
}
我将此代码放在
if (value == Runtime.PyNone && !obType.IsValueType) {
result = null;
return true;
}
https://github.com/pythonnet/pythonnet/blob/4df6105b98b302029e524c7ce36f7b3cb18crcer/cs >
这篇关于在Python中创建一个C#可空Int32(使用Python.NET)以使用可选的int参数调用C#方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!