属性(properties)被命名为类,结构和接口的成员。类或结构中的成员变量或方法称为字段。 属性是字段的扩展,并使用相同的语法访问。它们使用访问器,通过这些访问器可以读取,写入或操作私有字段的值。
属性不指定存储位置。它们有读取,写入或计算其值的访问器。
例如,假设有一个名称为student
的类,其中包含年龄(age
),名称(name
)和代码(code
)的私有字段。我们无法从类范围外直接访问这些字段,但是可以拥有访问这些私有字段的属性。
属性的访问器包含有助于获取(读取或计算)或设置(写入)属性的可执行语句。访问器声明可以包含get
访问器和set
访问器。例如:
// declare a code property of type string:
public string code
{
get
{
return code;
}
set
{
code = value;
}
}
// declare a name property of type string:
public string name
{
get
{
return name;
}
set
{
name = value;
}
}
// declare a age property of type int:
public int age
{
get
{
return age;
}
set
{
age = value;
}
}
以下示例演示了如何使用属性:
using system;
namespace h3
{
class student
{
private string code = "n.a";
private string name = "not known";
private int age = 0;
// declare a code property of type string:
public string code
{
get
{
return code;
}
set
{
code = value;
}
}
// declare a name property of type string:
public string name
{
get
{
return name;
}
set
{
name = value;
}
}
// declare a age property of type int:
public int age
{
get
{
return age;
}
set
{
age = value;
}
}
public override string tostring()
{
return "code = " + code +", name = " + name + ", age = " + age;
}
}
class exampledemo
{
public static void main()
{
// create a new student object:
student s = new student();
// setting code, name and the age of the student
s.code = "10010";
s.name = "maxsu";
s.age = 24;
console.writeline("student info: {0}", s);
//let us increase age
s.age += 1;
console.writeline("student info: {0}", s);
console.readkey();
}
}
}
当上述代码被编译并执行时,它产生以下结果:
student info: code = 10010, name = maxsu, age = 24
student info: code = 10010, name = maxsu, age = 25
抽象类可能有一个抽象属性,它应该在派生类中实现。以下程序说明了这一点:
using system;
namespace h3
{
public abstract class person
{
public abstract string name
{
get;
set;
}
public abstract int age
{
get;
set;
}
}
class student : person
{
private string code = "n.a";
private string name = "n.a";
private int age = 0;
// declare a code property of type string:
public string code
{
get
{
return code;
}
set
{
code = value;
}
}
// declare a name property of type string:
public override string name
{
get
{
return name;
}
set
{
name = value;
}
}
// declare a age property of type int:
public override int age
{
get
{
return age;
}
set
{
age = value;
}
}
public override string tostring()
{
return "code = " + code + ", name = " + name + ", age = " + age;
}
}
class exampledemo
{
public static void main()
{
// create a new student object:
student s = new student();
// setting code, name and the age of the student
s.code = "1011";
s.name = "maxsu";
s.age = 21;
console.writeline("student info:- {0}", s);
//let us increase age
s.age += 1;
console.writeline("student info:- {0}", s);
console.readkey();
}
}
}
当上述代码被编译并执行时,它产生以下结果:
student info:- code = 1011, name = maxsu, age = 21
student info:- code = 1011, name = maxsu, age = 22