装箱值类型十进制到可为空的对象?



我取消了两个可为空的object(object?(decimal并对返回结果的操作数执行一些算术...... (如果不可能,则引发异常(

如何将结果框回object?

编辑: 按照下面注释中的要求进行代码。

var baseValue = scope.GetByPath(localPath); //object?
var rhsValue = Rhs.Execute(scopeIterations); //object?

decimal res;
if (baseValue is decimal)
{
if (rhsValue is decimal)
{
switch (Operator)
{
case ArithmeticOperator.Add:
res = ConvertToDecimal(baseValue) + ConvertToDecimal(rhsValue);
object? foo = res;
break;
}
}

因此,在拳击resobject?时,我会收到IDE投诉。

这是来自一个库:

private static decimal ConvertToDecimal(object? value)
{
if (value != null)
{
if (value is string valueAsString)
{
return Convert.ToDecimal(valueAsString, (Some CultureInfo);
}
return Convert.ToDecimal(value);
}
throw new ArgumentNullException(nameof(value));
}

我不确定你为什么要这样做,可能有更好的方法。

无论如何,你总是可以投射的。在这里查看

int theInt = 8;
object theObject = theInt;
int? nullableInt = theInt;
Console.WriteLine($"{theInt} - {theObject} - {nullableInt}");

最新更新