chap03 C#中的物件導向

來源:互聯網
上載者:User

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();
}
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.