18.属性(1)

18.属性(1)_第1张图片

1.种方法

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            User sz = new User();
            sz.SetName( "小王");
            sz.SetSex( "牛");
            MessageBox.Show("姓名:" + sz.GetName()+"\r\n" + "性别:" + sz.GetSet());
        }       
    }
    class User
    {
        private  string m_Name;
        private  string m_Sex;
        public string GetName()
        {
            return m_Name;
        }
        public void SetName(string Values)
        {
            m_Name = Values;
        }
        public string GetSet()
        {
            return m_Sex;
        }
        public void SetSex(string Values)
        {
            if (Values == "男" || Values == "女")
            {
                m_Sex = Values;
            }
            else
            {
                MessageBox.Show("姓名必须是'男'或‘女’");
            }
        }

 

    }

2.种方法(采取使用属性也可以达到同样的效果)

public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void Form1_Load(object sender, EventArgs e)
        {
            User sz = new User();
            sz.Name = "小王";
            sz.Sex = "";
            MessageBox.Show("姓名:" + sz.Name + "\r\n" + "性别:" + sz.Sex);
        }       
    }
    class User
    {
        private string m_Name;
        private string m_Sex;
        public string Name
        {
            get
            {
                return m_Name;
            }
            set
            {
                m_Name =value;
            }
        }
        public string Sex
        {
            get
            {
                return m_Sex;
            }
            set
            {
                if (value == "男" || value == "女")
                {
                    m_Sex = value;
                }
                else
                {
                    MessageBox.Show("姓名必须写'男'或'女'");
                }
            }
        }

     }

你可能感兴趣的:(属性)