Вы можете сделать это с помощью With
методов, таких как:
// you need a separate overload to handle the case of not returning anything
public static void With<T>(T t, Action<T> block) {
block(t);
}
public static R With<T, R>(T t, Func<T, R> block) => block(t);
И затем вы можете using static
класс, в котором вы объявили методы, и использовать его вот так (переведенный код из здесь ):
var list = new List<string> {"one", "two", "three"};
With(list, x => {
Console.WriteLine($"'with' is called with argument {x}");
Console.WriteLine($"It contains {x.Count} elements");
});
var firstAndLast = With(list, x =>
$"The first element is {x.First()}. " +
$"The last element is {x.Last()}.");
В вашем примере это будет использоваться так:
static string PrintAlphabet() => With(new StringBuilder(), x => {
for (var c = 'A' ; c <= 'Z' ; c = (char)(c + 1)) {
x.Append(c);
}
return x.ToString();
});