How to define a type extension for T[] in F#?

前端 未结 2 430
粉色の甜心
粉色の甜心 2020-12-09 17:18

In C#, I can define an extension method for a generic array of type T like this:

public static T GetOrDefault(this T[] arr, int n)
{
    if (arr.Len         


        
2条回答
  •  孤街浪徒
    2020-12-09 17:54

    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:

    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
    

提交回复
热议问题