以下是一个简单的例子,演示了属性的基本形式和用法:
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
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
-
-
带参数存储过程写法
create or replace package body PKG_CheckVehicleInfo is– ...
[阅读全文]
-
-
-
-
-
-
-
-
网友评论