使用 IronPython 时如何处理 C# 小数?
How do I deal with C# decimals when using IronPython?
我是 IronPython 和 Python 的新手。我正在尝试使用 C# 小数和 IronPython 数学函数。当我尝试 return 一个参数的绝对值时,当参数是小数时我得到一个类型异常。这是我的代码:
[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
您始终可以选择导入 .NET Math
class 并使用其中的方法。
var pySrc =
@"def MyAbs(arg):
from System import Math
return Math.Abs(arg)";
我是 IronPython 和 Python 的新手。我正在尝试使用 C# 小数和 IronPython 数学函数。当我尝试 return 一个参数的绝对值时,当参数是小数时我得到一个类型异常。这是我的代码:
[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
您始终可以选择导入 .NET Math
class 并使用其中的方法。
var pySrc =
@"def MyAbs(arg):
from System import Math
return Math.Abs(arg)";