Индексаторы, свойства - C#
Формулировка задачи:
есть string[] ms
внутриего лежат слова
1) есть сво-во Site - возврощет размер массива
2) функция add() добоавлет новойслово в массив слов
void add(string s)
размер фиксированный!
т.е. если мыввели 2 слова, то size = 2;
индексаторы
1) public string this[int x]; - возврощает строку пономеру индекса
2) public int this[string s]; - -//-//-
если кто может, помогите,
так как то что в книгах анписано про индексаторы понятно все
а вот с эти попал в тупик..
комментам в коде буду очень рад!
main()
{
StringList sl = new StringList();
sl.add("sedfds");
sl.add("sdsdf");
// ...
// ...
// ..
}Решение задачи: «Индексаторы, свойства»
textual
Листинг программы
using System;
using System.Collections.Generic;
using System.Text;
class TempRecord
{
private string[] array = new string[5];
private int x = 0;
public int X //Свойство Х
{
get { return x; }
set
{
if (value >= 0)
x = value;
}
}
public string this[int i]
{
get
{
return array[i];
}
set
{
if (i < array.Length)
{
array[i] = value;
}
else throw new Exception("Your index is bigger then Length of array");
}
}
public int this[string s]
{
get
{
for(int i=0; i<array.Length; i++)
{
if(s == array[i])
return i;
}
return -1;
}
}
public void add(string s)
{
this[x] = s;
this.X++;
}
}
class MainClass
{
static void Main()
{
TempRecord sample = new TempRecord();
sample.add("1qweqwe");
sample.add("2qwerwe");
sample.add("3ewrer");
sample.add("4sedfsdf");
Console.WriteLine(sample[0]);
Console.WriteLine(sample[1]);
Console.WriteLine(sample[2]);
Console.WriteLine(sample[3]);
Console.WriteLine("\n---------------\n");
Console.WriteLine(sample["1qweqwe"]);
Console.WriteLine(sample["2qwerwe"]);
Console.WriteLine(sample["3ewrer"]);
Console.WriteLine(sample["4sedfsdf"]);
}
}