给定 type
对于各种属性,当属性为array
时如何提取属性的类型, list
或seq
?
下面的示例代码
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
执行上面的命令会得到以下属性,
- 姓名:
String
- 汽车:
IStructuralEquatable[]
- 姓名:
FSharpList<String>
- 其他:
IEnumerable<String>
- 其他2:
List<String>
应该如何extractTypeInfo
进行更新,以便结果将具有以下信息
- 姓名:
String
- 汽车:
Car
- 姓名:
String
- 其他:
String
- 其他2:
String
最佳答案
我倾向于做这样的事情:
let extractTypeInfo (typ:Type) =
typ.GetInterfaces()
|> Array.tryFind (fun iFace ->
iFace.IsGenericType && iFace.GetGenericTypeDefinition() = typedefof<seq<_>>)
|> Option.map (fun iFace -> iFace.GetGenericArguments().[0])
此方法捕获类型是否为 seq<'T>
通过返回 Some
或None
和 'T
的类型在 Some
的结果内案例。
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
关于.net - 获取序列的基础类型(数组、列表、seq),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42286136/