Mam do napisania metodę Wykonaj(), która dla podanych jako argument delegatów (procedur) wykona je kolejno na przechowywanej w klasie tablicy, np.:
tablica = new TablicaObliczeniowa(1, 2, 5, 4, 3);
tablica.Wykonaj(Array.Sort, Array.Reverse);
Console.WriteLine(tablica); // wypisze: [5, 4, 3, 2, 1]
Jako podpowiedź mam skorzystać z delegata action. Póki co udało mi się stworzyć coś takiego, ale dalej nie mam pojęcia jak to zrobić? Pomożecie?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Delegaty
{
class TablicaObliczeniowa
{
public int[] tab;
public TablicaObliczeniowa(params int[] list)
{
tab = new int[list.Length];
list.CopyTo(tab, 0);
}
public delegate int Operacja(int x, int y);
Operacja suma = (x, y) => x + y;
Operacja iloczyn = (x, y) => x * y;
public delegate void AutoOperacja(ref int x);
//AutoOperacja refIloczyn = (ref x) => x * x;
public int Oblicz(Operacja dzialanie)
{
int wynik = tab[0];
for (int i = 1; i < tab.Length; i++)
wynik = dzialanie(wynik, tab[i]);
return wynik;
}
public void Aplikuj(params AutoOperacja[] operacje)
{
foreach (var operacja in operacje)
for (int i = 0; i < tab.Length; i++)
operacja(ref tab[i]);
}
public void Wykonaj(params AutoOperacja[] operacja)
{
foreach (var operacje in operacja)
operacje(ref tab);
}
public override string ToString()
{
return "[" + string.Join(", ", tab) + "]";
}
}
class Program
{
static void Main(string[] args)
{
TablicaObliczeniowa tablica = new TablicaObliczeniowa(new int[] { 1, 2, 3, 4, 5 });
Console.WriteLine("Suma = " + tablica.Oblicz((x, y) => x + y));
tablica.Aplikuj((ref int x) => x *= x);
Console.WriteLine(tablica);
tablica.Aplikuj((ref int x) => x *= x, (ref int x) => x -= 1);
Console.WriteLine(tablica);
TablicaObliczeniowa.AutoOperacja operacja = null;
operacja = ((ref int x) => x *= x);
operacja += ((ref int x) => x -= 1);
//tablica.Aplikuj(operacja);
Console.WriteLine(tablica);
Console.ReadKey();
}
}
}