另外再补充两个C# 4.0的新特性可选参数与命名参数:

1、可选参数

  可选参数,顾名思义,它不是必需的。对于一般的参数,如果不为它指定值,可能会导出运行出错。但是可选参数不会。

  可选参数的规则:

  1、可选参数不能为参数列表第一个参数,它必须位于所有必选参数之后;

  2、可选参数必须指定一个默认值;

  3、可选参数的默认值必须是一个常量表达式;

  4、所有可选参数以后的参数都必须是可选参数。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace AllDemo
{
    public class Program
    {
        static void Main(string[] args)
        {
            int count1 = Plus(5);    //当不指定可选参数时,是默认值
            Console.WriteLine(count1);  //输出 15

            int count2 = Plus(5, 5); //当指定可选参数时,有默认值
            Console.WriteLine(count2);  //输出 10

            Console.ReadKey();
        }

        public static int Plus(int i, int j = 10)
        {
            return i + j;
        }
    }
}
View Code

相关文章:

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