Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
473 views
in Technique[技术] by (71.8m points)

f# - Static extension methods supporting member constraints

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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...