在F#中对对象调用方法的简写 [英] Shorthand for calling a method on an object in F#
问题描述
有没有一种方法可以像这样生成函数":
Is there a way to "generate" functions like this one:
fun x -> x.ToString
我希望能够将实例方法转换为以"this"为参数的静态方法,例如:
I would like to be able to turn an instance method into a static method which takes "this" as a parameter, like so:
items |> Seq.filter my_predicate |> Seq.map Object.ToString
推荐答案
在F#集线器上已对此进行了多次讨论.参见例如实例方法作为函数.据我所知,这是一个非常棘手的问题,因此,没有计划在F#的第一个版本中有这样的东西,但是最终拥有这样的东西将是很棒的:-).
this has been discussed several times on the F# hub. See for example instance methods as functions. This is quite tricky problem, so there are no plans to have something like this in the first version of F# as far as I know, but it would be great to have something like that eventually :-).
您可以采取的另一种解决方法是将静态成员添加为F#中的扩展方法:
Another workaround that you could do is to add static member as an extension method in F#:
type System.Object with
static member ObjToString(o:obj) = o.ToString()
open System
[ 1 .. 10 ] |> Seq.map Object.ObjToString;;
但这有点丑陋.另外,似乎仅当您对方法使用不同的名称时,此方法才有效.我想F#不允许您使用扩展方法重载现有方法,而总是偏向于固有方法.
But that is a bit ugly. Also, it seems that this works only if you use different name for the method. I guess that F# doesn't allow you to overload existing method with an extension method and always prefer the intrinsic one.
这篇关于在F#中对对象调用方法的简写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!