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() {
        }

        /// <summary>
        /// Farmer类的构造函数
        /// </summary>
        /// <param name="m_Name">Farmer的姓名参数</param>
        public Farmer(string m_Name) {
            name = m_Name;
        }

        /// <summary>
        /// 姓名字段
        /// </summary>
        string name = string.Empty;

        /// <summary>
        /// max字段
        /// </summary>
        const int max = 150;

        /// <summary>
        /// min字段
        /// </summary>
       const int min = 0;

        /// <summary>
        /// 年龄字段
        /// </summary>
        int age = 0;

        /// <summary>
        /// Max属性
        /// </summary>
        public int Max {
            get {
                return max;
            }
        }

        /// <summary>
        /// Min属性
        /// </summary>
        public int Min
        {
            get
            {
                return min;
            }
        }

        /// <summary>
        /// Name属性
        /// </summary>
        public string Name {
            set {
                name = value;
            }
        }

        /// <summary>
        /// 年龄属性
        /// </summary>
        public int Age {
            get {
                return age;
            }
            set {
                if ((value > min) && (value < max))
                {
                    age = value;
                }
                else
                {
                    try
                    {
                        Exception ex = new Exception("设置的值超出预设范围!");
                        throw (ex);
                    }
                    catch
                    {

                        Console.WriteLine("设置的值超出预设范围!");

                    }
                }
            }
        }
    }

}

原文地址:https://www.cnblogs.com/huyong/p/2685685.html