.net - 获取序列的基础类型(数组、列表、seq)

标签 .net f#

给定 type对于各种属性,当属性为array时如何提取属性的类型, listseq

下面的示例代码

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>通过返回 SomeNone'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/

相关文章:

.net - 在 F# 中使用 Lambda 表达式创建委托(delegate)

.net - 编译后如何自动运行测试?

.net - RestSharp for JSON 中的属性映射不起作用

.net - F# 代码不够通用(使用静态成员约束)

f# - 如何使用 vscode 在 F# 项目中强制文件排序?

linq - 在 F# 中为 C# 对象初始值设定项创建 LINQ 表达式

dynamic - 使用 F# 在类/接口(interface)中动态定义多个成员

f# - 如何改进这个 F# 功能

c# - 如何正确更改C#中RadioButton组当前选中的RadioButton

c# - C# 用户控件中的属性失败