简体   繁体   中英

Count members of a record type

Lets say I have the following type:

type BinaryOp =
    { Lhs: int
      Rhs: int
      Destination: int }

Is there a F# way of counting the members of that record, ie countMembers<BinaryOp> = 3 ? I know I could use System.Reflection but I'd rather not.

I do not think there is a way to do this without relying on the .NET reflection mechanism. However, the core F# library provides a convenient API on top of the .NET reflection for working with F# types. You can implement countMembers using the F# reflection API like this:

open Microsoft.FSharp.Reflection

let countMembers<'T> = 
  FSharpType.GetRecordFields(typeof<'T>).Length

I'm not sure why you want to do this, or why you want to avoid reflection - maybe there is a completely diferent design for what you actually want to achieve - but if you need to count the number of fields in a record, this is the best way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM