Использование делегата Action - C#
Формулировка задачи:
Добрый день. Имеется такая задача
Написать статический метод, выполняющий указанное действие над элементами матрицы целых чисел. Параметры: матрица целых чисел, заданное действие – объект Action.
Используя написанный метод:
• вывести матрицу на экран;
• вывести на экран положительные элементы матрицы;
• увеличить в два раза все положительные элементы матрицы (Для этого придется изменить тип параметра-делегата! Предыдущий вариант закомментировать ).
Не могу понять как реализовать 3-ий пункт. может кто сможет помочь.
И может можно как то более красиво реализовать вывод матрицы
Заранее спасибо .
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Задание_2
{
class Program
{
static void Metod(int[,] arr, Action<int, int> act)
{
for(int i=0;i<arr.GetLength(0);++i)
{
for(int j=0;j<arr.GetLength(1);++j)
{
act(arr[i, j], j);
}
}
}
static void Show(int num, int j)
{
if(j == 0)
Console.WriteLine();
Console.Write(num + "\t");
}
static void ShowPositive(int num, int j)
{
if(num>0)
Console.Write(num + "\t");
}
static void Change(ref int num, int j)
{
if (num > 0)
num *= 2;
}
static void Main(string[] args)
{
int[,] arr = new int[5, 5];
Random rand = new Random();
for (int i = 0; i < arr.GetLength(0); ++i)
{
for (int j = 0; j < arr.GetLength(1); ++j)
{
arr[i, j] = rand.Next(-10, 10);
}
}
Console.WriteLine("Матрица");
Metod(arr, Show);
Console.WriteLine();
Console.WriteLine("Положительные элементы матрицы");
Metod(arr, ShowPositive);
}
}
}Решение задачи: «Использование делегата Action»
textual
Листинг программы
class Program
{
static void Method(int[,] arr, Action<int> act)
{
for (int i = 0; i < arr.GetLength(0); i++)
for (int j = 0; j < arr.GetLength(1); j++)
act(arr[i, j]);
}
static void Method2(int[,] arr, Func<int, int> act)
{
for (int i = 0; i < arr.GetLength(0); i++)
for (int j = 0; j < arr.GetLength(1); j++)
arr[i, j] = act(arr[i, j]);
}
static void Show(int num)
{
Console.Write(num + "\t");
}
static void ShowPositive(int num)
{
if (num > 0)
Console.Write(num + "\t");
}
static int MultBy2(int num)
{
if (num > 0)
return num*2;
else
return num;
}
static void Main(string[] args)
{
int[,] arr = new int[5, 5];
Random rand = new Random();
for (int i = 0; i < arr.GetLength(0); i++)
for (int j = 0; j < arr.GetLength(1); j++)
arr[i, j] = rand.Next(-10, 10);
Console.WriteLine("Матрица");
Method(arr, Show);
Console.WriteLine();
Console.WriteLine("Положительные элементы матрицы");
Method(arr, ShowPositive);
Console.WriteLine();
Console.WriteLine("Положительные элементы матрицы, умноженные на 2");
Method2(arr, MultBy2);
Method(arr, ShowPositive);
Console.WriteLine();
Console.ReadLine();
}
}