码迷,mamicode.com
首页 > Windows程序 > 详细

C#中的set和get的用法

时间:2014-11-25 09:13:48      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   on   div   log   

//在C#中,可以通过set和get方式将属性设为”可写“和”可读“。set方式有一个隐藏参数value,它即是指向属性的参数。只是用get方式的属性,它将是一个只读属性,只能被访问,不能改变它的值
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication4
{
    public class Player
    {
        private string m_name = "";//私有,不能直接访问
        public string Name
        {
            set { m_name = value; }//通过访问Name属性改变m_name的值
            get { return m_name; }//通过访问Name属性获得m_name的值
        }
        private int m_life = 100;//私有,不能直接访问
        public int Life
        {
            get { return m_life; }//通过访问Life属性获得m_life的值
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Player player = new Player();
            player.Name = "player1";//OK
             //player.Life=10;//错误,Life是只读属性
            Console .WriteLine(player.Name);//输出Name
            Console .WriteLine(player.Life);//输出Life的值100
            //输入任意键退出
            Console.ReadKey();
        }
    }
}

 

C#中的set和get的用法

标签:style   blog   io   ar   color   sp   on   div   log   

原文地址:http://www.cnblogs.com/heisaijuzhen/p/4120117.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!