相当于C#typeof(IEnumerable<>)的F# [英] F# equivalent of the C# typeof(IEnumerable<>)

查看:136
本文介绍了相当于C#typeof(IEnumerable<>)的F#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段代码需要确定给定类型是否实现 IEnumerable< T> (我不在乎T)

I have a piece of code where I need to figure out if a given type implements IEnumerable<T> (I don't care about the T)

我已经尝试过了( t:System.Type ,如果您想知道的话)

I've tried (t:System.Type in case you wonder)

let interfaces = t.GetInterfaces()
let enumerbale = 
    interfaces.Any(fun t -> 
        t.GetGenericTypeDefinition() = typeof<IEnumerable<>>
    ) 

但是不会编译(编译不喜欢<>)。然后我尝试了

however that won't compile (the compile doesn't like the <>). I then tried

let interfaces = t.GetInterfaces()
let enumerbale = 
    interfaces.Any(fun t -> 
        t.GetGenericTypeDefinition() = typeof<IEnumerable<'a>>
    )

,但是得到警告, a是对obj的约束。我不想弄清楚是否实现了 IEnumerable< obj> ,但是 IEnumerabl<>

but get's a warning that 'a is constraint to obj. I Don't want to figure out if IEnumerable<obj> is implemented but IEnumerabl<>.

任何人都知道这是解决方案,并且btw也可以随时评论上面的代码。

Any one know's the solution and btw feel free to comment on the code above as well.

推荐答案

这应该起作用:

typedefof<System.IEnumerable<_>>

编辑

正如Tomas所指出的,这里的 _ 通配符没有什么特别的; F#推断类型 obj 是此上下文中最通用的类​​型,因此这与使用 typedefof< System.IEnumerable< obj>相同。 > 。但是,在某些情况下,这种工作方式可能会有些障碍。例如,如果您定义接口类型I<’a,当‘a:>我<’a>> =接口端,则您不能使用 typedefof< I< _>> ,因为 I< obj> 不满足泛型约束,F#无法推断出另一个更合适的类型。即使没有递归约束,也可能发生这种情况(例如,当时, type I 。 C#的方法,在类似的情况下效果很好。

As Tomas notes, there's nothing special about the _ wildcard here; F# infers that the type obj is the most general applicable type in this context, so this is the same as using typedefof<System.IEnumerable<obj>>. In some cases the way this works can be a bit of a hindrance, though. For instance, if you define an interface type I<'a when 'a :> I<'a>> = interface end, then you can't use typedefof<I<_>>, because I<obj> doesn't satisfy the generic constraint and F# can't infer another more appropriate type. This can happen even without recursive constraints (e.g. type I<'a when 'a : struct and 'a :> System.ICloneable> = interface end. This is in contrast to C#'s approach, which works perfectly fine in the analogous cases.

对于您的代码本身,我想您也想进行一些其他更改,例如在调用 GetGenericTypeDefinition 之前确保接口是通用的。这就是我编写测试函数的方式:

As to your code itself, I think you'll want to make some other changes, too, such as ensuring that the interface is generic before calling GetGenericTypeDefinition. Here's how I'd write the test function:

(fun t -> t.IsGenericType && (t.GetGenericTypeDefinition() = typedefof<_ seq>))

这篇关于相当于C#typeof(IEnumerable&lt;&gt;)的F#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆