在Python中创建一个C#Nullable Int32(使用Python.NET),使用可选的int参数调用C#方法
我正在使用Python.NET加载C#程序集以从Python调用C#代码。 这很干净,但是我遇到一个问题,调用一个如下所示的方法:
Our.Namespace.Proj.MyRepo中的方法:
OutputObject GetData(string user, int anID, int? anOptionalID= null)
我可以为存在可选的第三个参数的情况调用该方法,但是无法确定要为第三个参数传递什么以匹配null情况。
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表明最后一个参数应该是类型:
System.Nullable`1[System.Int32]
只是不确定如何创建一个与Null案例相匹配的对象。
有关如何创建C#识别的Null对象的任何建议? 我假设传递原生Python没有用,但事实并非如此。
[编辑]
这已经合并到pythonnet:
https://github.com/pythonnet/pythonnet/pull/460
我遇到了与可空原语相同的问题 – 在我看来,Python.NET不支持这些类型。 我通过在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; }
我没办法测试这个,但试试看
_repo.GetData('me', System.Int32(1), System.Nullable[System.Int32]())
既然你说可选参数是Nullable
,你需要在C#代码中创建一个Int32
类型的新Nullable
对象,或者new System.Nullable
。
我会假设第一个失败的例子会起作用,因为这是可选参数在C#中的工作方式; 在没有指定参数的情况下调用该函数。
你必须将参数传递给generics函数System.Nullable[System.Int32](0)