How do I implement a method with a variable number of arguments?

☆樱花仙子☆ 提交于 2021-01-27 12:05:09

问题


How do I implement a method with a variable number of arguments?

In C#, we can use the params keyword:

public class MyClass
{
    public static void UseParams(params int[] list)
    {
        for (int i = 0; i < list.Length; i++)
        {
            Console.Write(list[i] + " ");
        }
        Console.WriteLine();
    }
 }

So how can I do this in F#?

type MyClass() =

    member this.SomeMethod(params (args:string array)) = ()

I receive the following error from the code above:

The pattern discriminator 'params' is not defined

回答1:


You can use ParamArrayAttribute:

type MyClass() =
    member this.SomeMethod([<ParamArray>] (args:string array)) = Array.iter (printfn "%s") args

then:

let mc = MyClass()
mc.SomeMethod("a", "b", "c")


来源:https://stackoverflow.com/questions/42696008/how-do-i-implement-a-method-with-a-variable-number-of-arguments

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!