get,set总结

来源:互联网 发布:天津网络研究所地址 编辑:程序博客网 时间:2024/04/28 17:19
在许多面向对象程序设计语言中,属性(property)是指对象的特征和状态,具体地说就是指对象的数据成员。程序员可以指定数据成员能否被外界直接访问,如果数据成员被指定为public的,外界就可以用对象名.公有数据成员名访问该成员。c#是完全面向对象的语言,c#倡导一种新途径,对数据成员能够更好地封装和保护,同时又向外界提供更有效的访问形式。c#中用来达到这个目标的就是属性,而那些数据成员,在c#中称为字段


  属性的定义和使用
  属性由两个部分组成:属性头和存储器。存储器分为get访问器和set访问器。声明属性的一般形式为:

修饰符  学校名称不可修改
        private string stuName = "<span courier="" new";="" mso-hansi-font-family:"courier="" new";mso-bidi-font-family:"courier="" color:maroon;mso-font-kerning:0pt;"="" style="line-height: 21px; font-size: 9pt; font-family: 宋体; ">阿会楠";
        
private int stuAge = 22;
        
public string studentName
        {
            
get { return stuName; }
            
set { stuName = value; }
        }
        
public int studentAge
        {
            
get { return stuAge; }
            
set { stuAge = value; }
        }
        
public string studentCollege
        {
            
get { return stuCollege; }
        }
        
public string studentInfo
        {
            
get { return "<span courier="" new";="" mso-hansi-font-family:"courier="" new";mso-bidi-font-family:"courier="" color:maroon;mso-font-kerning:0pt;"="" style="line-height: 21px; font-size: 9pt; font-family: 宋体; ">学校:" + stuCollege + "<span courier="" new";="" mso-hansi-font-family:"courier="" new";mso-bidi-font-family:"courier="" color:maroon;mso-font-kerning:0pt;"="" style="line-height: 21px; font-size: 9pt; font-family: 宋体; ">名字:" + stuName + "<span courier="" new";="" mso-hansi-font-family:"courier="" new";mso-bidi-font-family:"courier="" color:maroon;mso-font-kerning:0pt;"="" style="line-height: 21px; font-size: 9pt; font-family: 宋体; ">岁数:" + stuAge;}
        }
    }

    class Program
    {
        
static void Main(string[] args)
        {
            Student stu = 
new Student();
            Console.Write(stu.studentCollege + 
"\n");
            stu.studentAge = 
25;
            Console.Write(stu.studentInfo);
            Console.ReadKey();
        }
    }
}