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

时间:2021-08-22 06:30:05

I'm new to IronPython and Python in general. I'm trying to work with C# decimals and IronPython math functions. When I try to return the absolute value of an argument, I get a type exception when the argument is a decimal. Here's my code:

我是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));
    }

The error message I get says:

我得到的错误消息说:

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

Is there a Python absolute value function that accepts decimals? If not, is it easy to write one? If I could specify the types of function parameters, I'd try to create my own abs function like this:

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

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

1 个解决方案

#1


1  

You always have the option to import the .NET Math class and use the methods there.

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

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

#1


1  

You always have the option to import the .NET Math class and use the methods there.

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

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