不说废话,直接上代码

 

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

namespace ArgsDemo
{
    /// <summary>
    /// 可选参数和命名参数
    /// </summary>
    class TestArgs
    {
        static void Main(string[] args)
        {
            new TestArgs().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 个参数的方法
            // 命名参数可按照不同顺序传递实参
            Console.ReadKey(true);
        }

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

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

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

 

 

结果:

C# 可选参数和命名参数 

 

相关文章:

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