天天看點

C#中的字段與屬性

using System;

using System.Collections.Generic;

using System.Text;

namespace Example11_1 {

    class Program {

        static void Main(string[] args) {

            Farmer farmer = new Farmer();

            farmer.Name = "Liu";

            farmer.Age = 226;

            Console.WriteLine(farmer.Age);

            Console.ReadLine();

        }

    }

    class Farmer {

        /// <summary>

        /// Farmer類的無參數構造函數

        /// </summary>

        public Farmer() {

        /// Farmer類的構造函數

        /// <param name="m_Name">Farmer的姓名參數</param>

        public Farmer(string m_Name) {

            name = m_Name;

        /// 姓名字段

        string name = string.Empty;

        /// max字段

        const int max = 150;

        /// min字段

       const int min = 0;

        /// 年齡字段

        int age = 0;

        /// Max屬性

        public int Max {

            get {

                return max;

            }

        /// Min屬性

        public int Min

        {

            get

            {

                return min;

        /// Name屬性

        public string Name {

            set {

                name = value;

        /// 年齡屬性

        public int Age {

                return age;

                if ((value > min) && (value < max))

                {

                    age = value;

                }

                else

                    try

                    {

                        Exception ex = new Exception("設定的值超出預設範圍!");

                        throw (ex);

                    }

                    catch

                        Console.WriteLine("設定的值超出預設範圍!");

}

本文轉自yonghu86 51CTO部落格,原文連結:http://blog.51cto.com/yonghu/1321455,如需轉載請自行聯系原作者