首页 > 代码库 > C#里类的get和set方法编写和调用

C#里类的get和set方法编写和调用

using System;
class Date
{
    int day;
    int month;
    int year;
    public int Day{
        get {
            return day; 
        }
        set {
            day = value; 
        }
    }
    

    public int Month{
        get { 
            return month;
        }
        set {
            month = value; 
        }
    }
    

    public int Year{
        get { 
            return year;
        }
        set {
            year = value;
        }
    }
    

    public bool IsLeapYear(int year)
    {
        return year%4== 0 ? true: false; 
    }
    public void SetDate (int day, int month, int year)
    {
        this.day = day;
        this.month = month;
        this.year = year;
    }
}

方法的调用

class User
{
  public static void Main()
  { 
        Date date = new Date(); 
        date.Day = 27; 
        date.Month = 6; 
        date.Year = 2003;
        Console.WriteLine
        ("Date: {0}/{1}/{2}", date.Day, date.Month, date.Year);
    }
}

 

C#里类的get和set方法编写和调用