[英]How to define a type extension for T[] in F#?
In C#, I can define an extension method for a generic array of type T like this: 在C#中,我可以为类型为T的泛型数组定义一个扩展方法,如下所示:
public static T GetOrDefault<T>(this T[] arr, int n)
{
if (arr.Length > n)
{
return arr[n];
}
return default(T);
}
but for the life of me I can't figure out how to do the same in F#! 但对于我的生活,我无法弄清楚如何在F#中做同样的事情! I tried
type 'a array with
, type array<'a> with
and type 'a[] with
and the compiler wasn't happy with any of them. 我尝试
type 'a array with
, type array<'a> with
并type 'a[] with
,编译器对它们中的任何一个都不满意。
Can anyone tell me what's the right to do this in F#? 谁能告诉我在F#中做这件事的权利是什么?
Sure, I can do this by overshadowing the Array module and add a function for that easily enough, but I really want to know how to do it as an extension method! 当然,我可以通过掩盖阵列模块并为此轻松添加功能来实现这一点,但我真的想知道如何将其作为扩展方法!
You have to write the array type using 'backtick marks' - like this: 你必须使用'反引号'来编写数组类型 - 像这样:
type 'a ``[]`` with
member x.GetOrDefault(n) =
if x.Length > n then x.[n]
else Unchecked.defaultof<'a>
let arr = [|1; 2; 3|]
arr.GetOrDefault(1) //2
arr.GetOrDefault(4) //0
Edit : The syntax type ``[]``<'a> with ...
seems to be allowed as well. 编辑 :似乎也允许语法
type ``[]``<'a> with ...
In the F# source (prim-types-prelude.fs) you can find the following definition: 在F#source(prim-types-prelude.fs)中,您可以找到以下定义:
type ``[]``<'T> = (# "!0[]" #)
Good question. 好问题。 I can't figure out how to extend
'T[]
but you can take advantage of the fact that arrays implement IList<_>
to do: 我无法弄清楚如何扩展
'T[]
但你可以利用数组实现IList<_>
的事实:
type System.Collections.Generic.IList<'T> with
member x.GetOrDefault(n) =
if x.Count > n then x.[n]
else Unchecked.defaultof<'T>
let arr = [|1; 2; 3|]
arr.GetOrDefault(1) //2
arr.GetOrDefault(4) //0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.