C#索引器簡單實例代碼
public class Fruit
{
string peach = "a round juicy fruit that has a soft yellow or red skin and a large hard seed in the center, or the tree that this fruit grows on";
string orange = "a round fruit that has a thick orange skin and is divided into parts inside";
string banana = "a long curved tropical fruit with a yellow skin";
string apple = "a hard round fruit that has red, light green, or yellow skin and is white inside ";
public string this[string fruitName]
{
get
{
switch (fruitName)
{
case "peach":
return peach;
case "orange":
return orange;
case "banana":
return banana;
case "apple":
return apple;
default:
throw new Exception("wrong fruit name");
}
}
set
{
switch (fruitName)
{
case "peach":
peach = value;
break;
case "orange":
orange = value;
break;
case "banana":
banana = value;
break;
case "apple":
apple = value;
break;
default:
throw new Exception("wrong fruit name");
}
}
}
}
class Program
{
static void Main(string[] args)
{
Fruit f = new Fruit();
//關(guān)聯(lián)數(shù)組的方式訪問get方法
Console.WriteLine(f["peach"]);
//關(guān)聯(lián)數(shù)組的方式訪問set方法
f["peach"] = "I like to eat peach.";
Console.WriteLine(f["peach"]);
Console.ReadLine();
}
}
相關(guān)文章
C#創(chuàng)建WebService接口并連接的全過程
工作時遇到需要請求客戶的接口返回數(shù)據(jù),要求使用WebService,借此機會記錄一下,下面這篇文章主要給大家介紹了關(guān)于C#創(chuàng)建WebService接口并連接的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-12-12
C#?使用EntityFramework?CodeFirst?創(chuàng)建PostgreSQL數(shù)據(jù)庫的詳細(xì)過程
這篇文章主要介紹了C#使用EntityFramework?CodeFirst創(chuàng)建PostgreSQL數(shù)據(jù)庫的過程,本文通過圖文并茂的形式給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-07-07
詳解c#中Array,ArrayList與List<T>的區(qū)別、共性與相互轉(zhuǎn)換
本文詳細(xì)講解了c#中Array,ArrayList與List<T>的區(qū)別、共性與相互轉(zhuǎn)換,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12

