使用 Seq.cast 时出现问题

发布于 2024-08-10 23:12:14 字数 415 浏览 7 评论 0原文

使用 Seq.cast 似乎总是失败,即使对于像下面这样简单的事情也是如此:

let xor c = Seq.cast c |> Seq.reduce (^^^)
xor [1;3]       // Works, assuming because no cast is necessary
xor ['a';'b']   // Fails
xor [2u]        // Fails

后两者因指定的强制转换无效而失败。我缺少什么?

我正在尝试使用 Seq.cast 将一堆内容转换为 uint16,但由于某种原因它总是失败(即使我用 Seq 注释它) .cast)。这是怎么回事?

Using Seq.cast seems to constantly fail, even for something as simple as the following:

let xor c = Seq.cast c |> Seq.reduce (^^^)
xor [1;3]       // Works, assuming because no cast is necessary
xor ['a';'b']   // Fails
xor [2u]        // Fails

The latter two fail with Specified Cast is not valid. What am I missing?

I'm trying to use Seq.cast to convert a bunch of stuff to uint16, but for some reason it always fails (even if I annotate it with Seq.cast<uint32>). What's up with this?

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

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

发布评论

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

评论(2

蔚蓝源自深海 2024-08-17 23:12:14

我相信这是因为 Seq.cast 只会执行类型 casts,而不是类型 coercion:你想要 Seq.map uint32 c |> Seq.reduce (^^^)

强制转换和强制转换之间的区别在于,当强制转换更改静态类型时,值会被解释为不更改其动态类型(例如:我知道这个 Animal 实际上是一个 Dog ),强制创造了一个全新的价值......至少从语言的角度来看。 CLR 中的划分似乎主要集中在值类型(强制)和引用类型(强制转换)之间,这使得保持直线更容易一些。

I believe this is because Seq.cast will only do type casts, rather that type coercion: you want Seq.map uint32 c |> Seq.reduce (^^^).

The difference between casting and coercing is that while casting changes the static type a value is interpreted as without changing it's dynamic type, (eg: I know this Animal is really a Dog), coercing creates a completely new value ... at least from the language point of view. The split in the CLR seems to be pretty much between value types (coercing) and reference types (casting), which makes it a bit easier to keep straight.

枉心 2024-08-17 23:12:14

另请参阅

此 C# 代码在 F# 中是什么样子? (第一部分:表达式和语句)

讨论了 C# 中的强制转换如何表示(至少)4 个不同的操作,以及每个不同的操作如何映射到特定的 F# 功能。

See also

What does this C# code look like in F#? (part one: expressions and statements)

which discusses how casts can mean (at least) 4 different operations in C#, and how each of those different operations maps to specific F# functionality.

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