zoukankan      html  css  js  c++  java
  • 方法的参数的默认值设置

    很惭愧用了C#这么久,今天才知道原来方法是可以设置参数的默认值的。话不多说,来演示一下:
    首先,定义了一个Student类。包括属性成员:ID、Name、Age 和方法成员:Print。其中,Print方法的参数都设置了默认值
    View Code
    public  class Student
        {
          public int ID { get; set; }
          public string Name{get;set;}
          public int Age { get; set; }
          /// <summary>
          /// 方法Print,默认传参 name ="test", age=-1
          /// </summary>
          /// <param name="name"></param>
          /// <param name="age"></param>
          public void Print(string name ="test",int age=-1)
          {
              Console.WriteLine("姓名:"+name);
              Console.WriteLine("年龄:"+age);
          }
        }

    然后,在主程序中声明一个Student类型的变量,并初始化字段,利用传参和不传参分别调用Print函数。
    View Code
     public  class Program
        {
            static void Main(string[] args)
            {
                Student student = new Student();
                student.Name = "小王";
                student.Age = 24;
                //直接调用Print函数,不传入参数
                student.Print();  
                //传入参入,调用Print
                student.Print(student.Name, student.Age);
            }
           
        }
    调用Print时,在智能提示下,是可以看到参数默认的值。

    最后程序运行结果:

    public  class Student
        {
          public int ID { get; set; }
          public string Name{get;set;}
          public int Age { get; set; }
          public void Print(string name ="test",int age=-1)
          {
              Console.WriteLine("姓名:"+name);
              Console.WriteLine("年龄:"+age);
          }
        }
  • 相关阅读:
    bs4抓取糗事百科
    数据结构(复习排序算法)——选泡插(选择,冒泡,插入,希尔)
    Hive-ha (十三)
    Hive优化(十一)
    Hive压缩和存储(十二)
    Hive权限管理(十)
    Hive的视图和索引(九)
    Hive动态分区和分桶(八)
    Hive(七)Hive参数操作和运行方式
    Redis 基础
  • 原文地址:https://www.cnblogs.com/fxie/p/2705529.html
Copyright © 2011-2022 走看看