Name Tuples/Anonymous Types in F#?

后端 未结 6 1650
执笔经年
执笔经年 2021-02-03 19:46

in C# you can do stuff like :

var a = new {name = \"cow\", sound = \"moooo\", omg = \"wtfbbq\"};

and in

6条回答
  •  庸人自扰
    2021-02-03 20:26

    You can't create "anonymous records" in F# - when using types, you can either use tuples which are anonymous, but don't carry labels or you can use records which have to be declared in advance and have labels:

    // Creating an anonymous tuple
    let route = ("Home", "Index", UrlParameter.Optional)
    
    // Declaration and creating of a record with named fields
    type Route = { controller : string; action : string; id : UrlParameter } 
    let route = { controller = "Home"; action = "Index"; id = UrlParameter.Optional } 
    

    Technically, the problem with anonymous records is that they would have to be defined as actual classes somewhere (the .NET runtime needs a type), but if the compiler put them in every assembly, then two anonymous records with same members might be different types if they were defined in different assemblies.

    Honestly, I think that the example you posted is just a poor design decision in ASP.NET - it is misusing a particular C# feature to do something for which it wasn't designed. It may not be as bad as this, but it's still odd. The library takes a C# anonymous type, but it uses it as a dictionary (i.e. it uses it just as a nice way to create key-value pairs, because the properties that you need to specify are dynamic).

    So, if you're using ASP.NET from F#, it is probably easier to use an alternative approach where you don't have to create records - if the ASP.NET API provides some alternative (As Daniel shows, there is a nicer way to write that).

提交回复
热议问题