将 obj 转换为通用 F# 接口
我试图将一个对象转换为一个通用接口,看起来像 这。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能只是坐在那里使用通用术语 - 但如果编译器可以推断出具体类型,那就没问题了。或者,正如错误消息所述,您可以转换为这样的函数:
否则,您需要一个具体的结果类型
,尽管这里您需要提前知道要拆箱的内容
,或者,如果代码可以推断出具体类型稍后根据您的使用情况,您会没事的。
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:
otherwise, you need a concrete type for result like
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.