Static extension methods supporting member constraints

99封情书 提交于 2019-12-17 16:59:36

问题


I need to implement a static extension method supporting member constraints on some basic primitive types like integers, floats, etc. Here's my code for signed integers:

module MyOperators =
    let inline foo (x : ^T) = (^T : (static member Foo : ^T -> int) (x)) 

    type System.Int32 with 
        static member Foo(x : Int32) = 7 // static extension

Test code:

open MyOperators    
let x = foo 5 // x should be 7

But compiler complains with error:

The type 'System.Int32' does not support any operators named 'Foo'

What am I missing here? Thanks!


回答1:


Static member constraints in F# never find 'extension methods', they can only see intrinsic methods on types (and a few special cases called out in the F# language spec).

Perhaps you can use method overloading instead? What is your ultimate goal?




回答2:


F#'s static type constraints don't work with extension methods. Extension methods cannot statically be checked at compile time, and even so, you can have multiple definitions for Int32::Foo (depending on which namespace you imported).

Unfortunately, to solve your problem you might have to resort to using reflection.



来源:https://stackoverflow.com/questions/3681142/static-extension-methods-supporting-member-constraints

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!