[英]How do I deal with C# decimals when using IronPython?
I'm new to IronPython and Python in general. 我是IronPython和Python的新手。 I'm trying to work with C# decimals and IronPython math functions.
我正在尝试使用C#小数和IronPython数学函数。 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:
这是我的代码:
[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? 有没有可以接受小数的Python绝对值函数? 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:
如果可以指定函数参数的类型,则尝试创建自己的abs函数,如下所示:
define abs(Decimal arg):
return arg < 0 ? -arg : arg
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)";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.