如何创建在F#的扩展方法,例如,像这样的C#扩展:如何创建扩展方法(F#)?
public static string Right(this string host, int index)
{
return host.Substring(host.Length - index);
}
如何创建在F#的扩展方法,例如,像这样的C#扩展:如何创建扩展方法(F#)?
public static string Right(this string host, int index)
{
return host.Substring(host.Length - index);
}
对于F#的扩展,可以从F#被称为:
type System.String with
member x.Right(index) = x.Substring(x.Length - index)
注意,为测试版1,这不会导致C#兼容的扩展方法。
要生成C#中可见的扩展方法(但不能用作F#中的扩展方法),请参阅Brian编辑原始文章中的链接。
我知道这并不能真正回答你的问题,但值得指出。在F#和其他函数式语言中,您经常会看到带有静态方法的模块(如Seq模块),这些模块被设计为与其他函数组合。据我所见,实例方法不容易编写,这就是这些模块存在的一个原因。在这个扩展的情况下,你可能想要为String模块添加一个函数。
module String =
let right n (x:string) =
if x.Length <= 2 then x
else x.Substring(x.Length - n)
然后它会像这样使用。
"test"
|> String.right 2 // Resulting in "st"
["test"; "test2"; "etc"]
|> List.map (String.right 2) // Resulting in ["st"; "t2"; "tc"]
虽然在这种情况下扩展方法不会更多的代码。
["test"; "test2"; "etc"]
|> List.map (fun x -> x.Right 2)
darn,这就是我想要的。 – esac 2009-10-06 04:51:07