6

我正在使用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 会起作用,但事实并非如此。

4

3 回答 3

4

[编辑]

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

于 2014-12-05T19:45:45.613 回答
2

我无法对此进行测试,但请尝试

_repo.GetData('me', System.Int32(1), System.Nullable[System.Int32]())

由于您说可选参数是Nullable,因此您需要创建一个新Nullable的 type 对象Int32,或者new System.Nullable<int>()在 C# 代码中。

我会假设第一个失败的例子会起作用,因为这是可选参数在 C# 中的工作方式;调用函数而不指定参数。

于 2014-11-05T05:32:06.953 回答
1

您必须将参数传递给通用函数System.Nullable[System.Int32](0)

于 2017-03-27T04:45:31.507 回答