zoukankan      html  css  js  c++  java
  • 可选参数与命名参数

    另外再补充两个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

    2、命名参数

      可选参数解决的是参数默认值的问题,而命名参数解决的是参数顺序的问题,命名参数将我们从记忆每个方法数目繁多的参数列表中解放了出来。让你可以不按顺序输入参数。

    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)
            {
                //string str = "字符串";
                //int i = 10;
                //Console.WriteLine(Plus(str:str,i:i));     //虽然很怪异,但这3行代码是能正常运行的
    
                Console.WriteLine(Plus(str: "字符串", i: 10));      //注意顺序与方法签名参数中的不一样
    
                Console.ReadKey();
            }
    
            public static string Plus(int i, string str)
            {
                return str + i.ToString();
            }
        }
    }
    View Code
  • 相关阅读:
    es6简述
    vue梳理
    webpack常用插件
    JS知识点
    CSS知识点
    224646
    223301
    图书馆 摘 1
    消息队列高手课 笔记6
    消息队列高手课 笔记5
  • 原文地址:https://www.cnblogs.com/scmail81/p/8683384.html
Copyright © 2011-2022 走看看