gpt4 book ai didi

clojure - 将惰性行序列写入 ClojureClr 中的文件而不进行反射

转载 作者:行者123 更新时间:2023-12-02 17:19:26 26 4
gpt4 key购买 nike

我有一大堆延迟序列行,我想写入文件。在 C# 中,我会使用 System.IO.File/WriteAllLines它有一个过载,其中的行是 string[]IEnumerable<string> .

我想在运行时不使用反射来执行此操作。

(set! *warn-on-reflection* true)

(defn spit-lines [^String filename seq]
(System.IO.File/WriteAllLines filename seq))

但是,我收到了这个反射警告。

Reflection warning, ... - call to WriteAllLines can't be resolved.

一般来说,出于性能原因,我需要知道何时需要反射,但我不关心这个特定的方法调用。我愿意编写更多代码来消除警告,但不愿意将所有数据作为数组强制放入内存中。有什么建议吗?

最佳答案

这里有两个需要考虑的选项,具体取决于您是否使用 Clojure 的核心数据结构。

从 seq 转换为 IEnumerable<string>Enumerable.Cast来自 LINQ

此选项适用于任何 IEnumerable仅包含字符串。

(defn spit-lines [^String filename a-seq]
(->> a-seq
(System.Linq.Enumerable/Cast (type-args System.String))
(System.IO.File/WriteAllLines filename)))

键入提示以强制调用者提供 IEnumerable<string>

如果您想使用类型提示,请执行此操作。但请注意,clojure 数据结构未实现 IEnumerable<String> ,因此这可能会导致运行时异常

^|System.Collections.Generic.IEnumerable`1[System.String]|

将类型的完整 CLR 名称包装在垂直管道 ( | ) 中可以让您指定在 Clojure 语法中非法的字符。

(defn spit-lines [^String filename ^|System.Collections.Generic.IEnumerable`1[System.String]| enumerable-of-string]
(System.IO.File/WriteAllLines filename enumerable-of-string))

这是 (spit-lines "filename.txt" #{}) 的异常(exception)情况将集合传递给类型提示版本时:

System.InvalidCastException: Unable to cast object of type 'clojure.lang.PersistentTreeSet' to type 'System.Collections.Generic.IEnumerable`1[System.String]'.

有关specifying types的更多信息.

关于clojure - 将惰性行序列写入 ClojureClr 中的文件而不进行反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26615180/

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