get、set读写属性详解

来源:互联网 发布:买电脑在京东还是淘宝 编辑:程序博客网 时间:2024/06/06 02:49

get、set读写属性

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
    class TimePeriod
    {
        private double seconds;

        public double Hours
        {           
            //将Hours的值处理过后传递给私有变量seconds
            set { seconds = value * 3600; }
            //将处理过后的值返回给公有变量Hours
            get { return seconds/2; }
        }
        public double test()
        {
            return seconds;
        }

    }

    class Program
    {
        static void Main()
        {
            //创建TimePeriod类的一个对象
            TimePeriod t = new TimePeriod();
            //将值传递给公有变量Hours
            t.Hours = 24;
            //利用公有方法test返回私有变量seconds处理过后的值
            System.Console.WriteLine("seconds="+t.test());
            //输出公有变量Hours的值
            System.Console.WriteLine("Hours=" + t.Hours);
            Console.ReadLine();
            //输出结果seconds=86400,Hours=43200
        }
    }
}

原创粉丝点击