当前位置: 移动技术网 > IT编程>开发语言>.net > .net get set用法小结第1/3页

.net get set用法小结第1/3页

2018年04月22日  | 移动技术网IT编程  | 我要评论

以下是一个简单的例子,演示了属性的基本形式和用法:
using system;
using system.collections.generic;
using system.text; 
namespace 属性的用法
{
    public class student
    {
        private string stuname = "阿会楠";
        public string studentname
        {
            get { return stuname; }
            set { stuname = value; }
        }
    }
    class program
    {
        static void main(string[] args)
        {
            student stu = new student();
            console.write(stu.studentname);
            console.readkey();
        }
    }
}

       上面代码中定义了一个属性studentname,它包含get访问器和set访问器。属性studentname封装了类student中的字段stuname,字段如果没有加访问控制符,被默认为private,外界不能直接访问它,现在外界可以通过studentname属性自由地存取stuname字段了。

       属性的get和set都是可执行的程序语句组合,具有行为的特点;而使用具有get访问器和set访问器的属性时候就像使用字段一样,即可以作为左值接受数据,又可以作为右值输出数据,系统正是按照属性出现在语句中的位置,自动地选择是调用get还是调用set。
2

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网