在Python中创建C#可空Int32(使用Python.NET)以使用可选的int参数调用C#方法

发布于 2021-01-29 14:10:59

我正在使用Python.NET加载C#程序集以从Python调用C#代码。这很干净,但是我在调​​用如下所示的方法时遇到了问题:

Our.Namespace.Proj.MyRepo中的方法:

OutputObject GetData(string user, int anID, int? anOptionalID= 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 None可以,但是不能。

关注者
0
被浏览
108
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    [编辑]

    这已合并到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;
    }
    

    https://github.com/pythonnet/pythonnet/blob/4df6105b98b302029e524c7ce36f7b3cb18f7040/src/runtime/converter.cs#L320



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看