gpt4 book ai didi

f# - 当基类实现 IEnumerable 时实现 IEnumerable<'T>

转载 作者:行者123 更新时间:2023-12-04 11:58:23 25 4
gpt4 key购买 nike

有没有简洁的实现方式IEnumerable<'T>在其基类型实现非泛型 IEnumerable 的类型中?我正在使用 mkEnumerator下面的函数可以做到这一点,但似乎过分了。

open System
open System.Collections.Generic
open System.Configuration

let mkEnumerator<'T> (e : System.Collections.IEnumerator) =
{ new IEnumerator<'T> with
member __.Current = e.Current |> unbox
interface System.Collections.IEnumerator with
member __.Current = e.Current
member __.MoveNext() = e.MoveNext()
member __.Reset() = e.Reset()
interface IDisposable with
member __.Dispose() =
match e with
| :? IDisposable as d -> d.Dispose()
| _ -> () }

type MyConfigElement() =
inherit ConfigurationElement()

type MyConfigCollection() =
inherit ConfigurationElementCollection()
override __.CreateNewElement() = Unchecked.defaultof<_>
override __.GetElementKey(_) = Unchecked.defaultof<_>
interface IEnumerable<MyConfigElement> with
member __.GetEnumerator() = mkEnumerator<MyConfigElement> (base.GetEnumerator())

更新

按照 desco 的建议,我现在使用:
type MyConfigCollection() =
inherit ConfigurationElementCollection()
...
interface IEnumerable<MyConfigElement> with
member __.GetEnumerator() = (Seq.cast<MyConfigElement> this).GetEnumerator()

最佳答案

布莱恩建议的简短版本:

let mkEnum<'T> (ie : System.Collections.IEnumerable) = (Seq.cast<'T> ie).GetEnumerator()

关于f# - 当基类实现 IEnumerable 时实现 IEnumerable<'T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8438244/

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