using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace 可选参数和命名参数
{
    class Program
    {
        static void Main(string[] args)
        {
            (new Program()).run();
        }

        private void run()
        {
            Display(6);                 // 调用有 1 个参数的方法
            Display(a: 99);             // 调用有 1 个参数的方法
            Display(aaaa: 99);          // 调用有 2 个参数的方法,命名参数 aaaa 限制,
            Display(6, 8);              // 调用有 2 个参数的方法
            Display(6, 8, 10);          // 调用有 3 个参数的方法
            Display(6, b: 9);           // 调用有 2 个参数的方法,选择最贴近的
            Display(6, c: 10);          // 调用有 3 个参数的方法,命名参数 c 限制
            Display(6, c: 12, b: 8);    // 调用有 3 个参数的方法
                                        // 方法中 a 为必选参数,位置不能改变
            Display(c: 12, a: 8, b: 10);    // 调用有 3 个参数的方法
                                            // 命名参数可按照不同顺序传递实参
        }

        public void Display(int a)
        {
            Console.WriteLine("调用有 1 个参数的方法!");
            Console.WriteLine("a = {0}", a);
            Console.WriteLine();
        }

        public void Display(int aaaa = 99, double b = 2)    // aaaa 和 b 均为可选参数
        {
            Console.WriteLine("调用有 2 个参数的方法!");
            Console.WriteLine("a = {0}, b = {1}", aaaa, b);
            Console.WriteLine();
        }

        public void Display(int a, double b = 2, int c = 6) // b、c 是可选参数
                                                            // a 是必选参数
        {
            Console.WriteLine("调用有 3 个参数的方法!");
            Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
            Console.WriteLine();
        }
    }
}

 运行后结果如下:

C#中可选参数和命名参数的定义及使用

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-09-16
  • 2022-12-23
  • 2021-08-17
  • 2021-10-02
  • 2021-10-14
猜你喜欢
  • 2021-12-29
  • 2021-11-23
  • 2022-12-23
  • 2021-07-06
  • 2021-10-10
  • 2022-12-23
相关资源
相似解决方案