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);
          }
        }
  • 相关阅读:
    canvas-color的几种设置
    canvas-2lineCap.html
    canvas-2lineJoin.html
    canvas-0trasform.html
    总体、个体和简单随机样本
    大数定律
    切比雪夫不等式
    B1032. 挖掘机技术哪家强
    Array(数组)对象-->join() 方法
    Array(数组)对象-->shift() 方法
  • 原文地址:https://www.cnblogs.com/fxie/p/2705529.html
Copyright © 2011-2022 走看看