给定.Net类型,比方说typeof<string>,在运行时如何创建等效的string list = []?
我的动机是,当使用FSharpValue.MakeRecord基于解析的值创建记录时,需要将值作为a传递obj[].我一直在使用这些参数进行投射,box除了列表之外还有效.我遇到的问题是空的无类型列表列表不能装箱然后取消装箱.返回的具体错误是:
System.InvalidCastException: Unable to cast object of type
'Microsoft.FSharp.Collections.FSharpList`1[System.Object]'
to type
'Microsoft.FSharp.Collections.FSharpList`1[System.String]'.
Run Code Online (Sandbox Code Playgroud)
一个空的类型列表可以装箱和取消装箱,所以我试图找到一种方法将列表转换为运行时类型,例如typeof <>返回的类型,但没有运气.
type Test = {Names : string list}
// fails
let genericList = []
{Names = unbox (box genericList)}
//works
let typedList : string list = []
{Names = unbox (box typedList)}
//works
let genericNonEmptyList = ["Bill"]
{Names = unbox (box genericNonEmptyList)}
Run Code Online (Sandbox Code Playgroud) 如果我定义了一个实现带有附加属性的接口的记录,则接口属性不会被 json.net 序列化。如何让 json.net 序列化这些接口属性。这是一个例子
open Newtonsoft.Json
type IRecord =
abstract member id : string
type ARec = {
Name : string
} with
interface IRecord with
member this.id = this.Name
let aRec = {Name = "John"}
Run Code Online (Sandbox Code Playgroud)
都JsonConvert.SerializeObject aRec和JsonConvert.SerializeObject (aRec :> IRecord)结果,{"Name":"John"}但我期望{"Name":"John"; "id":"John"}
我尝试添加ShouldSerializeid到界面,但没有任何区别。
给定带有类型参数的类型,是否可以创建包含具有混合具体类型的值的列表?请参阅下面的代码.一切正常,直到我尝试创建list2,其中一些元素具有数据的int,而其他元素具有浮点数.有没有办法做到这一点?我在list3中的尝试无法编译.
type Holder<'data> = {
Data : 'data
Name : String
}
let intVal =
{Data = 23;
Name = "Bill"}
let intVal2 =
{Data = 29;
Name = "Cindy"}
let floatVal =
{Data = 23.0;
Name = "John"}
let list1 = [intVal; intVal2]
let list2 = [intVal; floatVal]
let list3 : Holder<'a> list = [intVal; floatVal]
Run Code Online (Sandbox Code Playgroud) 我一直是f#测试库Canopy的用户,它的工作原理很棒。但是我不知道如何让它针对浏览器堆栈上的浏览器。我确实找到了这个,但是有可能。
有没有更好的方法来编写addValues下面的功能?似乎应该可以使用模式匹配而不是FSharp.Reflection但我看不到它.
open System
open FSharp.Reflection
type Value =
| Tag1 of decimal
| Tag2 of decimal
| Error of string
let addValues v1 v2 =
let c1, f1 = FSharpValue.GetUnionFields(v1, v1.GetType())
let c2, f2 = FSharpValue.GetUnionFields(v2, v2.GetType())
let amt1 = (f1.[0]) :?> decimal
let amt2 = (f2.[0]) :?> decimal
if c1 = c2
then ((FSharpValue.MakeUnion(c1, [|box (amt1 + amt2)|]))) :?> Value
else Error "Mixed Tags"
Run Code Online (Sandbox Code Playgroud)
这可以这样使用:
addValues (Tag1 22m) (Tag1 10m) //Value = Tag1 32M
addValues (Tag1 22m) …Run Code Online (Sandbox Code Playgroud) 这不会编译。为什么?错误消息令人困惑,为什么模式中不存在该属性?
match System.Net.Http.HttpMethod.Post with
| System.Net.Http.HttpMethod.Post -> "post"
| _ -> "other"
Run Code Online (Sandbox Code Playgroud)