Telegram Group & Telegram Channel
✔️ Задача. Что выведет на консоль этот пример на C#?


using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
var funcs = new List<Func<int>>();

// Первая группа лямбд
for (int i = 0; i < 4; i++)
{
funcs.Add(() => i * i);
}

Console.Write("Squares: ");
foreach (var f in funcs)
Console.Write(f() + " ");

Console.WriteLine();

// Вторая группа лямбд с копией переменной
funcs.Clear();
for (int i = 0; i < 4; i++)
{
int j = i;
funcs.Add(() => j * j);
}

Console.Write("SquaresWithCopy: ");
foreach (var f in funcs)
Console.Write(f() + " ");
}
}

Ответ:
Squares: 16 16 16 16
SquaresWithCopy: 0 1 4 9

Объяснение
Первая группа лямбд
Лямбды захватывают переменную i по ссылке. К моменту, когда мы их вызываем в foreach, цикл уже завершился, поэтому i == 4. Каждая лямбда вычисляет 4 * 4 → 16.

Вторая группа лямбд
Внутри цикла для каждого значения i создаётся новая локальная переменная j, и лямбда захватывает именно её. При первой итерации j = 0, при второй j = 1 и т. д. Поэтому j * j даёт 0, 1, 4, 9 соответственно.

Такой приём (захват локальной копии переменной) позволяет избежать «одинообразного» результата и сохранить значение каждой итерации.
Please open Telegram to view this post
VIEW IN TELEGRAM



tg-me.com/csharp_ci/1346
Create:
Last Update:

✔️ Задача. Что выведет на консоль этот пример на C#?


using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
var funcs = new List<Func<int>>();

// Первая группа лямбд
for (int i = 0; i < 4; i++)
{
funcs.Add(() => i * i);
}

Console.Write("Squares: ");
foreach (var f in funcs)
Console.Write(f() + " ");

Console.WriteLine();

// Вторая группа лямбд с копией переменной
funcs.Clear();
for (int i = 0; i < 4; i++)
{
int j = i;
funcs.Add(() => j * j);
}

Console.Write("SquaresWithCopy: ");
foreach (var f in funcs)
Console.Write(f() + " ");
}
}

Ответ:
Squares: 16 16 16 16
SquaresWithCopy: 0 1 4 9

Объяснение
Первая группа лямбд
Лямбды захватывают переменную i по ссылке. К моменту, когда мы их вызываем в foreach, цикл уже завершился, поэтому i == 4. Каждая лямбда вычисляет 4 * 4 → 16.

Вторая группа лямбд
Внутри цикла для каждого значения i создаётся новая локальная переменная j, и лямбда захватывает именно её. При первой итерации j = 0, при второй j = 1 и т. д. Поэтому j * j даёт 0, 1, 4, 9 соответственно.

Такой приём (захват локальной копии переменной) позволяет избежать «одинообразного» результата и сохранить значение каждой итерации.

BY C# (C Sharp) programming


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/csharp_ci/1346

View MORE
Open in Telegram


C C Sharp programming Telegram | DID YOU KNOW?

Date: |

A project of our size needs at least a few hundred million dollars per year to keep going,” Mr. Durov wrote in his public channel on Telegram late last year. “While doing that, we will remain independent and stay true to our values, redefining how a tech company should operate.

How To Find Channels On Telegram?

There are multiple ways you can search for Telegram channels. One of the methods is really logical and you should all know it by now. We’re talking about using Telegram’s native search option. Make sure to download Telegram from the official website or update it to the latest version, using this link. Once you’ve installed Telegram, you can simply open the app and use the search bar. Tap on the magnifier icon and search for a channel that might interest you (e.g. Marvel comics). Even though this is the easiest method for searching Telegram channels, it isn’t the best one. This method is limited because it shows you only a couple of results per search.

C C Sharp programming from sg


Telegram C# (C Sharp) programming
FROM USA