gpt4 book ai didi

.net - F# 转换为编译时未知的类型

转载 作者:行者123 更新时间:2023-12-02 09:43:11 25 4
gpt4 key购买 nike

如何转换给定的对象列表。

let l = [1. :> obj; 2. :> obj]

当原始类型(在本例中为 float)在编译时未知时返回 float 列表?

我已经尝试过(以表明我对此知之甚少:)):

let t = (l |> List.head).GetType();
l |> List.map (fun e -> e :?> t)

这非常失败。

let castMe (ty : Type) (arr : obj list)  =
let m = typeof<Enumerable>.GetMethod("Cast")
let m = m.MakeGenericMethod([|ty|])
m.Invoke(null, [|arr|]) :?> System.Collections.Generic.IEnumerable<_>

let t = (l |> List.head).GetType();
l |> castMe t;;

失败的原因是:

error FS0030: Value restriction. The value 'it' has been inferred to have generic type val it : Generic.IEnumerable<'_a> Either define 'it' as a simple data term, make it a function with explicit arguments or, if you do not intend for it to be generic, add a type annotation.

================================================

编辑:

我会尝试解释我想要实现的目标以及到目前为止我所取得的成果,因为也许我根本没有采取正确的方法。

这是我用来保存我为其提供类型的数据的结构。

type public InnerData(query, table) =
...
member __.Data = data // map <string, obj list>
member __.Headers = headers // Dictionary <string, Type>

这是我的类型提供程序的构造函数。

ty.AddMember(ProvidedConstructor([], InvokeCode = fun [] -> <@@ InnerData(queryParam, tableNameParam) :> obj @@>))

这是我如何定义表示字典键的属性。看看评论。

do mdsTy.DefineStaticParameters([tableNameParam; queueryParam], fun tyName [| :? string as tableNameParam; :? string as queryParam |] ->
let ty = ProvidedTypeDefinition(
asm,
ns,
tyName,
baseType = Some(typeof<obj>))

let mdsInner = MdsData(mdsQueryParam, tableNameParam)

for header in mdsInner.Headers do
let columnName = header.Key
let columnType = header.Value

let arrayType = typedefof<IEnumerable<_>>.MakeGenericType(typeof<obj>)
// This works, but returns obj list. I would like to return a list of columnType that represents the downcasted version of arraytype.

let property = ProvidedProperty(columnName, arrayType,
GetterCode = fun [innerType] -> <@@ ((%%innerType:obj) :?> InnerData).Data.[columnName] @@>)
ty.AddMember(property)

在这里,我尝试使用上述方法(反射和:?>)来转换数据,但没有任何运气。

最佳答案

没有任何语法,因为正如 Wesley Wiser 指出的那样,无论如何你都无法对这样的表达式执行任何操作。但是,由于您正在处理 Expr 值,因此可以使用 Expr.Coerce 方法来创建与您想要的等效的表达式树。

关于.net - F# 转换为编译时未知的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20998486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com