Delegate Usage : Business Applications

后端 未结 8 1260
青春惊慌失措
青春惊慌失措 2021-01-03 02:46

Background

Given that \'most\' developers are Business application developers, the features of our favorite programming languages are used in the context of what we

8条回答
  •  青春惊慌失措
    2021-01-03 03:19

    Delegates become extremely powerful when you start looking at them as functional constructs

    .Net 2.0 included support for anonymous delegates, which formed the kernel of some of the functional concepts which were expanded upon by Linq. The syntax for an anonymous delegate is a bit bulkier than what Lambda's offer, but a lot of the core functional patterns are there in 2.0.

    In the List generic type you have the following items you can work with:

    1. ConvertAll() - Uses a delegate to convert all the members of the list into another type (T). This is basically an implementation of a Map Function
    2. Find() and FindAll, both take delegates, and will return you either a single item (in the case of Find()), or all items that cause the delegate passed in to evaluate to true. This provides a Filter function, and also the definition of a Predicate (a function which evaluates to a boolean)
    3. There is an implementation of a ForEach() method which takes a delegate. Allowing you to perform an arbitrary operation against each element in the list.

    Appart from List specific items, when your using anonymous delegates context is handled correctly, so you can implement Closure like structures. Or, on a more practicle level do something like:

    ILog logger = new Logger();
    MyItemICareAbout.Changed += delegate(myItem) { logger.Log(myItem.CurrentValue); };    
    

    And it just works.

    There is also the DynamicMethod stuff, which allows you to define bits of IL (using Reflection.Emit), and compile them as delegates. This gives you a nice alternative to pure reflection for things like Mapping layers, and data access code.

    Delegates are really a construct that allows you to represent executable code as data. Once you get your head around what that means, there are a whole lot of things that can be done. The support for these constructs in 2.0 was rudimentary when compared to 3.5, but still there, and still quite powerful.

提交回复
热议问题