代码之家  ›  专栏  ›  技术社区  ›  Дима Соколов

C#-与Kotlin中的with关键字类似?

  •  1
  • Дима Соколов  · 技术社区  · 5 年前

    像这样减少重复代码的数量:

    fun printAlphabet() = with(StringBuilder()){
        for (letter in 'A'..'Z'){
            append(letter)
        }
        toString()
    }
    

    有什么设施吗?

    0 回复  |  直到 5 年前
        1
  •  2
  •   Sweeper    5 年前

    你可以用 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();
        });