使用IronPython时如何处理c#小数?

本文关键字:处理 小数 IronPython 何处理 使用 | 更新日期: 2023-09-27 18:04:50

我是IronPython和Python的新手。我正在尝试使用c#小数和IronPython数学函数。当我尝试返回参数的绝对值时,如果参数是小数,就会得到类型异常。下面是我的代码:

    [TestMethod]
    public void CallDecimal()
    {
        var pySrc =
@"def MyAbs(arg):
    return abs(arg)";
        // host python and execute script
        var engine = IronPython.Hosting.Python.CreateEngine();
        var scope = engine.CreateScope();
        engine.Execute(pySrc, scope);
        // get function with a strongly typed signature
        var myAbs = scope.GetVariable<Func<decimal, decimal>>("MyAbs");
        Assert.AreEqual(5m, myAbs(-5m));
    }

我得到的错误信息是:

IronPython.Runtime.Exceptions.TypeErrorException: bad operand type for abs(): 'Decimal'

是否有接受小数的Python绝对值函数?如果没有,写一篇是否容易?如果我可以指定函数参数的类型,我会尝试创建自己的abs函数,如下所示:

define abs(Decimal arg):
    return arg < 0 ? -arg : arg

使用IronPython时如何处理c#小数?

您始终可以选择导入. net Math类并使用其中的方法。

var pySrc =
@"def MyAbs(arg):
    from System import Math
    return Math.Abs(arg)";