Индексатор с защитой от выхода - C#
Формулировка задачи:
Создайте индексатор с методами доступа get и set для класса MyClass, который будет проверять, выходит ли индекс за диапазон массива. В случае, если выходит – геттер будет возвращать строку "index out of range", а сеттер – просто не выполнять присвоение.
Исходник
Решил, но не правильно
using System;
namespace Less05_task03
{
class Program
{
static void Main(string[] args)
{
MyClass instance = new MyClass();
Console.WriteLine(instance[2]);
//выход за пределы массива
Console.WriteLine(instance[10]);
Console.ReadKey();
}
}
class MyClass
{
string[] array = new string[3] { "one", "two", "three" };
}
}using System;
namespace Less05_task03
{
class Program
{
static void Main(string[] args)
{
MyClass instance = new MyClass();
Console.WriteLine(instance[2]);
//выход за пределы массива
Console.WriteLine(instance[10]);
Console.ReadKey();
}
}
class MyClass
{
string[] array = new string[3] { "one", "two", "three" };
public string this[string index]
{
set
{
for (int i = 0; i < array.Length;i++ )
if (array[3] == index )
{
array[3] += index;
}
}
get
{
for (int i = 0; i < array.Length; i++)
if (array[3] == index)
{
return string.Format("ok");
}
else return string.Format("index out of range");
return string.Format("ok");
}
}
}
}
О, вот так додумался))
class MyClass
{
string[] array = new string[3] { "one", "two", "three" };
public string this[int index]
{
set
{
if ( 0 >= index || index < 4 )
{
}
}
get
{
if (0 >= index || index < 4)
{
return string.Format("ok");
}
else return string.Format("index out of range");
}
}
}
Не, на сайте с проверкой, пишет не верно(
Не, на сайте с проверкой, пишет не верно(
Решение задачи: «Индексатор с защитой от выхода»
textual
Листинг программы
class MyClass
{
string[] array = new string[3] { "one", "two", "three" };
public string this[int index]
{
get
{
if (index >= 0 && index < array.Length)
return array[index];
else
return "index out of range";
}
set
{
if (index >= 0 && index < array.Length)
array[index] = value;
}
}
}