您好,登錄后才能下訂單哦!
這篇文章主要講解了“C#索引指示器怎么使用”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來(lái)研究和學(xué)習(xí)“C#索引指示器怎么使用”吧!
C#索引指示器并不難使用。它們的用法跟數(shù)組相同。在一個(gè)類內(nèi)部,你可以按照你的意愿來(lái)管理一組數(shù)據(jù)的集合。這些對(duì)象可以是類成員的有限集合,也可以是另外一個(gè)數(shù)組,或者是一些復(fù)雜的數(shù)據(jù)結(jié)構(gòu)。不考慮類的內(nèi)部實(shí)現(xiàn),其數(shù)據(jù)可以通過(guò)使用C#索引指示器來(lái)獲得。
實(shí)現(xiàn)C#索引指示器(indexer)的類可以象數(shù)組那樣使用其實(shí)例后的對(duì)象,但與數(shù)組不同的是C#索引指示器的參數(shù)類型不僅限于int。簡(jiǎn)單來(lái)說(shuō),其本質(zhì)就是一個(gè)含參數(shù)屬性:
using System;
using System.Collections.Generic;
using System.Text;
namespace Example08
{
public class Point
{
private double x, y;
public Point(double X, double Y)
{
x = X;
y = Y;
}
//重寫ToString方法方便輸出
public override string ToString()
{
return String.Format("X: {0} , Y: {1}", x, y);
}
}
public class Points
{
Point[] points;
public Points(Point[] Points)
{
points = Points;
}
public int PointNumber
{
get
{
return points.Length;
}
}
//實(shí)現(xiàn)索引訪問(wèn)器
public Point this[int Index]
{
get
{
return points[Index];
}
}
}
//感謝watson hua(http://huazhihao.cnblogs.com/)的指點(diǎn)
//索引指示器的實(shí)質(zhì)是含參屬性,參數(shù)并不只限于int
class WeatherOfWeek
{
public string this[int Index]
{
get
{
//注意case段使用return直接返回所以不需要break
switch (Index)
{
case 0:
{
return "Today is cloudy!";
}
case 5:
{
return "Today is thundershower!";
}
default:
{
return "Today is fine!";
}
}
}
}
public string this[string Day]
{
get
{
string TodayWeather = null;
//switch的標(biāo)準(zhǔn)寫法
switch (Day)
{
case "Sunday":
{
TodayWeather = "Today is cloudy!";
break;
}
case "Friday":
{
TodayWeather = "Today is thundershower!";
break;
}
default:
{
TodayWeather = "Today is fine!";
break;
}
}
return TodayWeather;
}
}
}
class Program
{
static void Main(string[] args)
{
Point[] tmpPoints = new Point[10];
for (int i = 0; i < tmpPoints.Length; i++)
{
tmpPoints[i] = new Point(i, Math.Sin(i));
}
Points tmpObj = new Points(tmpPoints);
for (int i = 0; i < tmpObj.PointNumber; i++)
{
Console.WriteLine(tmpObj[i]);
}
string[] Week = new string[]
{ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Staurday"};WeatherOfWeek tmpWeatherOfWeek = new WeatherOfWeek();
for (int i = 0; i < 6; i++)
{
Console.WriteLine(tmpWeatherOfWeek[i]);
}
foreach (string tmpDay in Week)
{
Console.WriteLine(tmpWeatherOfWeek[tmpDay]);
}
Console.ReadLine();
}
}
}
感謝各位的閱讀,以上就是“C#索引指示器怎么使用”的內(nèi)容了,經(jīng)過(guò)本文的學(xué)習(xí)后,相信大家對(duì)C#索引指示器怎么使用這一問(wèn)題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。