C# 4.0,可选参数和params不能一起工作 [英] C# 4.0, optional parameters and params do not work together

查看:15
本文介绍了C# 4.0,可选参数和params不能一起工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建具有可选参数和参数的方法?

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());
}   

推荐答案

您现在唯一的选择是重载 TestOptional(就像您在 C# 4 之前必须做的那样).不是首选,但它会在使用时清理代码.

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());
}

这篇关于C# 4.0,可选参数和params不能一起工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆