C#4.0,可选的参数,而params不一起工作可选、参数、工作、params

由网友(纵使悲凉也是情)分享简介:我怎样才能创建一个具有可选参数,而params在一起的方法? 静态无效的主要(字串[] args){TestOptional(A,C:D,E); //这不会建TestOptional(A,C:D); //这样做的工作,但我只能设置1参数到Console.ReadLine();}公共静态无效TestOptional(...

我怎样才能创建一个具有可选参数,而params在一起的方法?

 静态无效的主要(字串[] args)
{

    TestOptional(A,C:D,E); //这不会建
    TestOptional(A,C:D); //这样做的工作,但我只能设置1参数
    到Console.ReadLine();
}

公共静态无效TestOptional(字符串A,INT B = 0,则params的String [] C)
{
    Console.WriteLine(A);
    Console.WriteLine(B);
    Console.WriteLine(C.Count());
}
 

解决方案

您唯一的选择,现在是重载TestOptional(因为你有C#4前做)。没有preferred,但它清理code在使用点。

 公共静态无效TestOptional(字符串A,PARAMS字符串[] C)
{
    TestOptional(A,O,C);
}

公共静态无效TestOptional(字符串A,INT B,PARAMS字符串[] C)
{
    Console.WriteLine(A);
    Console.WriteLine(B);
    Console.WriteLine(C.Count());
}
 
不再打磨P10,魅族新机魅蓝E2和魅蓝E参数对比

How can i create a method that has optional parameters and params together?

static void Main(string[] args)
{

    TestOptional("A",C: "D", "E");//this will not build
    TestOptional("A",C: "D"); //this does work , but i can only set 1 param
    Console.ReadLine();
}

public static void TestOptional(string A, int B = 0, params string[] C)
{
    Console.WriteLine(A);
    Console.WriteLine(B);
    Console.WriteLine(C.Count());
}   

解决方案

Your only option right now is to overload the TestOptional (as you had to do before C# 4). Not preferred, but it cleans up the code at the point of usage.

public static void TestOptional(string A, params string[] C)
{
    TestOptional(A, 0, C);
}

public static void TestOptional(string A, int B, params string[] C)
{
    Console.WriteLine(A);
    Console.WriteLine(B);
    Console.WriteLine(C.Count());
}

阅读全文

相关推荐

最新文章