以下是一个简单的例子,演示了属性的基本形式和用法:
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。
文章评论
共有 位脚本之家网友发表了评论我来说两句