chap03 C#中的面向对象

1. 哲学中的静态和动态属性分别对应于属性和行为。

2. 静态方法通过类名来访问,静态方法只能访问静态成员,非静态方法可以访问所有成员。

3. 属性和索引器的使用。

4. 访问类型修饰符public,private, protected, internal。

5. 静态成员可以在创建对象之前使用。


例子:

using System;

public class CD
{
public string name;
public double price;
public string type;
public CD(string name, double price, string type)
{this.name = name; this.price = price; this.type = type;}

}
public class VideoShop
{
private CD[] cdSet = new CD[10000];
private int cdCount = 0;
public int Count { get { return this.cdCount; } }
// 1. 第一个索引类型
public CD this[string cdName]
{
get
{
foreach (CD item in cdSet)
if (item.name == cdName)
return item;
return null;
}
}
// 2. 第二个索引类型
public CD this[string cdName, string type]
{
get
{
foreach (CD item in cdSet)
if (item.name == cdName && item.type == type)
return item;
return null;
}
}
// 3. 第三个索引类型
public CD this[int n]
{
set
{
if (cdSet[n] == null) cdCount++;
if (value == null && cdSet[n] != null) cdCount--;
cdSet[n] = value;
}
get
{
return cdSet[n];
}
}
}
class Test
{
[STAThread]
static void Main(string[] args)
{
VideoShop myshop = new VideoShop();
CD cd1 = new CD("金陵十三钗", 45, "DVD");
CD cd2 = new CD("罗马假日", 25, "VCD");
myshop[myshop.Count] = cd1; // 调用索引类型 3
myshop[myshop.Count] = cd2; // 调用索引类型 3
CD a = myshop["金陵十三钗"]; // 调用索引类型 1
CD b = myshop["罗马假日", "VCD"]; // 调用索引类型 2
Console.WriteLine("名称:{0}{1}, 价格:{2}", a.type, a.name, a.price);
Console.WriteLine("名称:{0}{1}, 价格:{2}", b.type, b.name, b.price);
Console.ReadLine();
}
}



posted @ 2012-03-07 20:39  Let it be!  阅读(173)  评论(0编辑  收藏  举报