我尝试将C#代码转换为F#
Items = new List<Item>
{
new Item
{
Product = "",
Category = "",
Quantity = 1,
Detail = "",
Price = 220
}
}
按照代码F#:
let items = ResizeArray<Item>()
items.Add(Item(
Product = "",
Category = "",
Quantity = 1,
Detail = "",
Price = 220))
let body =
OrderRequest(
Items = items)
如何直接在Items
属性中实例化?无需创建新变量,然后创建一个Add()
。等于第一个C#代码。
我已经尝试过这种方法,但是它不起作用:
let body =
OrderRequest(
Items = ResizeArray<Item>(Item(
Product = "",
Category = "",
Quantity = 1,
Detail = "",
Price = 220)))
我得到一个错误:
Error FS0193 Possible overhead: 'Generic.List (collection:
Generic.IEnumerable <Item>): ResizeArray <Item>'.
Incompatible type restrictions. The 'Item'
type is not compatible with
type 'Generic.IEnumerable <Item>'
答案 0 :(得分:0)
如果Items
的类型为IEnumerable<Item>
(又名Seq<Item>
),则可以编写:
let body =
OrderRequest(
Items =
[ Item(
Product = "",
Category = "",
Quantity = 1,
Detail = "",
Price = 220) ]
)
答案 1 :(得分:0)
如果OrderRequest
构造函数使用IEnumerable<T>
,则可以执行@VasilyKirichenko的建议。否则,如果实际上需要ResizeArray
,我建议您阅读以下内容:
let body =
seq { Item (Product = "",
Category = "",
Quantity = 1,
Detail = "",
Price = 220) }
|> fun li -> ResizeArray<_> li
|> fun ra -> OrderRequest (Items = ra)