Nullable double的嵌套运行时强制 [英] nested runtime coercion for a Nullable double

查看:123
本文介绍了Nullable double的嵌套运行时强制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个定义为佣金公式的值

Let's say I have a value defined as a sort of commission formula

let address_commission = 1.0 // minimal simplified example

我想将上述佣金应用于我从数据库中读取的金额(代码来自我在生产中使用的WCF服务窗口)

and I want to apply the above said commission to an amount I'm reading from the DB (the code is from a window WCF service I have in production)

let address_commission = 1.0 // minimal simplified example
new Model.ClaimModel( 
  //RequestRow = i, recounting
  Code = (row.["claim_code"] :?> string), 
  EvtDate = (row.["event_date"] :?> DateTime),
  // skipping lines...
  Amount = (row.["amount"] :?> double) * address_commission,

现在我看到金额行可以正常编译,但是我还需要在下面添加相同的佣金

now I see that the amount line compiles fine, but I also need to include the same commission in the following

PrevAmount = (if row.IsNull("prev_amount")  then Nullable()  else  (row.["prev_amount"] :?> Nullable<double>)),

这是错误的,因为The type 'float' does not match the type 'obj'

因此,我也尝试过

PrevAmount = (if row.IsNull("prev_amount")  then Nullable()  else  (((row.["prev_amount"] :?> double) * address_commission) :?> Nullable<double>)),

,但也会失败,并显示The type 'double' does not have any proper subtypes and cannot be used as the source of a type test or runtime coercion.

but it also fails with The type 'double' does not have any proper subtypes and cannot be used as the source of a type test or runtime coercion.

处理此问题的正确方法是什么?

What is the correct way to handle this?

推荐答案

:?>是动态转换,仅在运行时进行检查,因此最好避免使用它.如果要访问数据库,则打开open FSharp.Linq.NullableOperators

:?> is a dynamic cast and it's only checked at run-time so better try to avoid it. If you are accessing databases it helps to open the open FSharp.Linq.NullableOperators namespace. (The link is gone for me but it's somewhere on docs or msdn). Then you can use ?*? and similar operators. For example:

let x = System.Nullable<float> 4.
let y = x ?* 3.0
//val y : System.Nullable<float> = 12.0

您可以在任一侧或两侧都有?.

You can have ? on either or both sides.

您将获得一个Nullable浮点数,您可以将其强制转换为 Option.ofNullable(y)或双精度float y.

You will get back a Nullable float which you can coerce to an option with Option.ofNullable(y) or to a double float y.

这篇关于Nullable double的嵌套运行时强制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆