你可以用
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
声明方法的类,并像这样使用它(从
here
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();
});