属性
属性是类、结构和接口的命名成员。类或结构中的成员变量或方法称为字段。属性是对字段的一种扩展,并且使用相同的语法进行访问。它们通过访问器来读取、写入或操作私有字段的值。
属性并不命名存储位置。相反,它们具有访问器来读取、写入或计算其值。
访问器
属性的访问器包含有助于获取(读取或计算)或设置(写入)属性的可执行语句。访问器声明可以包含一个获取访问器、一个设置访问器或两者都有。例如:
public string Code {
get {
return code;
}
set {
code = value;
}
}
public string Name {
get {
return name;
}
set {
name = value;
}
}
public int Age {
get {
return age;
}
set {
age = value;
}
}
示例
以下示例演示了属性的使用:
using System;
namespace tutorialspoint {
class Student {
private string code = "N.A";
private string name = "not known";
private int age = 0;
public string Code {
get {
return code;
}
set {
code = value;
}
}
public string Name {
get {
return name;
}
set {
name = value;
}
}
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() {
Student s = new Student();
s.Code = "001";
s.Name = "Zara";
s.Age = 9;
Console.WriteLine("Student Info: {0}", s);
s.Age += 1;
Console.WriteLine("Student Info: {0}", s);
Console.ReadKey();
}
}
}
当上述代码被编译和执行时,它会产生以下结果:
Student Info: Code = 001, Name = Zara, Age = 9
Student Info: Code = 001, Name = Zara, Age = 10
抽象属性
抽象类可以具有抽象属性,该属性应在派生类中实现。下面的程序说明了这一点:
using System;
namespace tutorialspoint {
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;
public string Code {
get {
return code;
}
set {
code = value;
}
}
public override string Name {
get {
return name;
}
set {
name = value;
}
}
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() {
Student s = new Student();
s.Code = "001";
s.Name = "Zara";
s.Age = 9;
Console.WriteLine("Student Info:- {0}", s);
s.Age += 1;
Console.WriteLine("Student Info:- {0}", s);
Console.ReadKey();
}
}
}
当上述代码被编译和执行时,它会产生以下结果:
Student Info: Code = 001, Name = Zara, Age = 9
Student Info: Code = 001, Name = Zara, Age = 10