将 obj 转换为通用 F# 接口

发布于 2024-12-15 17:50:57 字数 631 浏览 3 评论 0原文

我试图将一个对象转换为一个通用接口,看起来像 这。

type IFetchData<'a> = 
     abstract FetchData: string -> seq<'a>

然而,我的示例用法在 FSI 中如下所示:

let sample = new Sample()
let box_sample = box(sample) //simulate reflection type that implements interface
let result = unbox<IFetchData<_>>(box_sample) //value restriction
let result2: IFetchData<_> = unbox<IFetchData<_>>(box_sample) //value restriction

我正在尝试实现类型成员 FetchData 的动态调用。 所以一旦我收到类型 IFetchData<_>;然后我想调用 FetchData 成员,而不需要知道泛型类型实际上是什么。

我收到的错误是值限制错误。 任何帮助将不胜感激。

谢谢。

I'm trying to cast an object to a generic interface that looks something like
this.

type IFetchData<'a> = 
     abstract FetchData: string -> seq<'a>

My example usage however looks like the following in FSI:

let sample = new Sample()
let box_sample = box(sample) //simulate reflection type that implements interface
let result = unbox<IFetchData<_>>(box_sample) //value restriction
let result2: IFetchData<_> = unbox<IFetchData<_>>(box_sample) //value restriction

I'm trying to achieve dynamic invocation of the type member FetchData.
so once I receive type IFetchData<_> then I'd like to invoke the FetchData member with out needing to know what the generic type actually is.

The error that I'm getting is a Value Restriction error.
Any help would be appreciated.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

女皇必胜 2024-12-22 17:50:57

你不能只是坐在那里使用通用术语 - 但如果编译器可以推断出具体类型,那就没问题了。或者,正如错误消息所述,您可以转换为这样的函数:

let result() = unbox<IFetchData<_>>(box_sample)

否则,您需要一个具体的结果类型

let result2 = unbox<IFetchData<char>>(box_sample)

,尽管这里您需要提前知道要拆箱的内容

,或者,如果代码可以推断出具体类型稍后根据您的使用情况,您会没事的。

You can't have generic terms just sitting around - but if the compiler can infer a concrete type you are fine. Alternatively, as the error message states you can convert to a function like this:

let result() = unbox<IFetchData<_>>(box_sample)

otherwise, you need a concrete type for result like

let result2 = unbox<IFetchData<char>>(box_sample)

although, here you need to know what you are unboxing to in advance

alternatively, if the code can infer a concrete type later based on your usage you will be fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文