我有一个大的懒散的行,我想写入一个文件。在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))但是我收到了反射警告。
反射警告,.-无法解析对WriteAllLines的调用。
通常,出于性能原因,我需要知道什么时候需要反射,但我并不关心这个特定的方法调用。我愿意编写更多代码来消除警告,但不愿意将所有数据作为数组强制进入内存。有什么建议吗?
发布于 2014-10-30 17:13:27
以下是两个需要考虑的选项,取决于您是否使用Clojure的核心数据结构。
使用LINQ中的IEnumerable<string>将seq转换为Enumerable.Cast
此选项适用于任何只包含字符串的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>
如果要使用类型提示,请执行以下操作。但是要注意,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" #{})有一个例外:
'System.Collections.Generic.IEnumerable`1System.String'.:无法将“clojure.lang.PersistentTreeSet”类型的对象强制转换为System.InvalidCastException
有关指定类型的更多信息。
https://stackoverflow.com/questions/26615180
复制相似问题