首页 > 代码库 > C#可选参数与具名参数

C#可选参数与具名参数

可选参数

static void test1()
{
    func1("A");
    func1("B", 30);
    Console.ReadKey();
}
static void func1(string name, int age = 20)
{
    Console.WriteLine("Name: " + name + "\t Age: " + age);
}

具名参数

static void test2()
{
    func2("C", 40);
    func2(age: 50, name: "D");
    Console.ReadKey();
}
static void func2(string name, int age)
{
    Console.WriteLine("Name: " + name + "\t Age: " + age);
}

可选参数与具名参数结合

static void test3()
{
    func3("E");
    func3("F", 10, false);
    func3("G", 15);
    func3("H", isMale: false);
    Console.ReadKey();
}
static void func3(string name, int age = 20, bool isMale = true)
{
    Console.WriteLine("Name: " + name + "\t Age: " + age + "\t IsMale: " + isMale);
}

 

C#可选参数与具名参数