方法的参数的默认值设置

很惭愧用了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);
      }
    }
posted @ 2012-09-27 13:54  碎念的风  阅读(524)  评论(1编辑  收藏  举报