属性
using System;
namespace runoob
{
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;
// 声明类型为 string 的 Code 属性
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
// 声明类型为 string 的 Name 属性
public override string Name
{
get
{
return name;
}
set
{
name = value;
}
}
// 声明类型为 int 的 Age 属性
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 对象
Student s = new Student();
// 设置 student 的 code、name 和 age
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();
}
}
}
上述代码是关于属性的例子。
属性:
属性是对于类中域的扩展,也就是为了给我们提供一个可以修改field的方法。
通过get { return age; }
实现读操作。
通过set { age = value; }
实现写操作。
value是通过使用访问器附的值。
那么我在学习过程中有一个疑问,为什么需要规定这么复杂的事情,我直接把想读写的领域不设置为私有,外界随意访问不就好了?
首先,我们通过访问器,即属性对领域设置为只读操作,或者只写操作,或者读写都可以。毫无疑问这在实际应用中有着非常大的需求,很多字段可能只其中一个需求,因此我们可以通过只定义一个方法来保证需求
其次,属性很好的保证了面向对象的思想,不可以对字段进行随意的改动,而是通过方法修改字段,实现与外界的隔离。
索引器
索引器的概念和属性类似,也是通过定义set和get访问器来使用的。
不同的是,在属性的基础上,可以操作更加详细的数据,不一定是类中的某个成员。
using System;
namespace IndexerApplication
{
class IndexedNames
{
private string[] namelist = new string[size];
static public int size = 10;
public IndexedNames()
{
for (int i = 0; i < size; i++)
namelist[i] = "N. A.";
}
public string this[int index]
{
get
{
string tmp;
if( index >= 0 && index <= size-1 )
{
tmp = namelist[index];
}
else
{
tmp = "";
}
return ( tmp );
}
set
{
if( index >= 0 && index <= size-1 )
{
namelist[index] = value;
}
}
}
static void Main(string[] args)
{
IndexedNames names = new IndexedNames();
names[0] = "Zara";
names[1] = "Riz";
names[2] = "Nuha";
names[3] = "Asif";
names[4] = "Davinder";
names[5] = "Sunil";
names[6] = "Rubic";
for ( int i = 0; i < IndexedNames.size; i++ )
{
Console.WriteLine(names[i]);
}
Console.ReadKey();
}
}
}
它通过[]来索引得到类中的某个信息。实现如上述代码。总的看起来,索引器的实现很像是把类当成了一个字典。return的内容是值,类型是定义方法的返回类型,键就是定义的索引器传入的值和类型,当作理解。
同样,value是通过等号右边的值来获得的。