Closures: why are they so useful?

前端 未结 10 668
渐次进展
渐次进展 2020-12-07 10:04

As an OO developer, maybe I have difficulty seeing its value. What added value do they give? Do they fit in an OO world?

10条回答
  •  天命终不由人
    2020-12-07 10:43

    Closures fit pretty well into an OO world.

    As an example, consider C# 3.0: It has closures and many other functional aspects, but is still a very object-oriented language.

    In my experience, the functional aspects of C# tend to stay within the implementation of class members, and not so much as part of the public API my objects end up exposing.

    As such, the use of closures tend to be implementation details in otherwise object-oriented code.

    I use them all the time, as this code snippet from one of our unit tests (against Moq) shows:

    var typeName = configuration.GetType().AssemblyQualifiedName;
    
    var activationServiceMock = new Mock();
    activationServiceMock.Setup(s => s.CreateInstance(typeName)).Returns(configuration).Verifiable();
    

    It would have been pretty hard to specify the input value (typeName) as part of the Mock expectation if it hadn't been for C#'s closure feature.

提交回复
热议问题