Классы - поля, конструкторы, свойства - C#
Формулировка задачи:
Должны присутствовать: - конструктор - методы задания (с контролем правильности) и чтения полей класса, класс список значений. Поля: Список (массив целых чисел) размер списка (целое число).
Для этого же класса написать методы: включение элемента в список исключение элемента из списка
Решение задачи: «Классы - поля, конструкторы, свойства»
textual
Листинг программы
using System;
class Program
{
static void Main()
{
List list = new List();
list.Add(3);
list.Add(-5);
list.Add(7);
list.Add(2);
list.RemoveAt(1);
Console.WriteLine(list.Count);
for (long i = 0; i < list.Count; i++)
Console.WriteLine("list[{0}] = {1}", i, list[i]);
}
}
sealed class List
{
private const long STEP = 2;
private long[] array;
public List()
: this(STEP) { }
public List(long size)
{
if (size < 1)
throw new ArgumentException();
array = new long[size];
Count = 0;
}
public List(List other)
{
if (other == null)
throw new ArgumentNullException();
this.array = new long[other.Count];
this.Count = other.Count;
Array.Copy(other.array, this.array, other.Count);
}
public long Count { get; private set; }
public void Add(long value)
{
if (Count == array.Length)
Extend();
array[Count++] = value;
}
public void RemoveAt(long index)
{
CheckBound(index);
Count--;
for (long i = index; i < Count; i++)
array[i] = array[i + 1];
}
public long this[long index]
{
get
{
CheckBound(index);
return array[index];
}
set
{
CheckBound(index);
array[index] = value;
}
}
private void Extend()
{
long[] temp = new long[Count + STEP];
Array.Copy(array, temp, Count);
array = temp;
}
private void CheckBound(long index)
{
if (index < 0 || index >= Count)
throw new ArgumentException("Выход за границу списка.", "index");
}
}