Get the base type for the sequence (array, list, seq)

Given typewith various properties, how to extract the type of a property when a property array, listor seq?

Code example below

type Car = { name: string }
type CarStore = 
    { name: string
    cars: Car[]
    names: string list
    others: string seq
    others2: ResizeArray<string> }

let peek x =
    Dump x
    x

let extractTypeInfo name (typ:Type) =
    let isEnumerable = true //todo: true for list, array, seq, etc
    let underlyingType = typ //todo: if isEnumerable = true, get actual type
    isEnumerable, underlyingType

typeof<CarStore>.GetProperties()
|> peek
|> Seq.map (fun p -> extractTypeInfo p.Name p.PropertyType)
|> Dump

The implementation of the above gives the following properties:

  • name: String
  • cars: IStructuralEquatable[]
  • names: FSharpList<String>
  • others: IEnumerable<String>
  • others2: List<String>

How to update extractTypeInfoto get the following information

  • name: String
  • cars: Car
  • names: String
  • others: String
  • others2: String
+4
source share
2 answers

I would be inclined to do something like this:

let extractTypeInfo (typ:Type) =
    typ.GetInterfaces()
    |> Array.tryFind (fun iFace -> 
        iFace.IsGenericType && iFace.GetGenericTypeDefinition() = typedefof<seq<_>>)
    |> Option.map (fun iFace -> iFace.GetGenericArguments().[0]) 

This approach captures whether the type is a seq<'T>return Someor a Nonetype 'Tas a result of the event Some.

Some examples in FSI:

extractTypeInfo typeof<float array>;;
val it : System.Type option =
  Some
    System.Double ...

extractTypeInfo typeof<string list>;;
val it : System.Type option =
  Some
    System.String ...

extractTypeInfo typeof<int>;;
val it : System.Type option = None
+8
source

@ TheInnerLight , , , , , .

, :

  • F # , , API .NET. , typ.IsGenericType false, typ.IsArray true, typ.GetElementType(). , API .NET.
  • generic type IEnumerable<'a> - . , , , , seqs , . , , IEnumerable<'a> ( ) IEnumerable<'a> ( ).

, , .

+5

Source: https://habr.com/ru/post/1670000/


All Articles