Delegate Usage : Business Applications

后端 未结 8 1238
青春惊慌失措
青春惊慌失措 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:21

    I think this question reflects the many ways to skin a cat. I find delegates (and lambdas) nearly as fundamental as a "for" loop.

    Here's one context in which I used delegates recently (formatting and names changed for presentation purposes:)

    protected T[] SortLines(Func createLine, IEnumerable unsorted)
    where T : LineType
    {
        Func, IEnumerable> sorter = (lines => lines);
    
        switch (settings.OrderSort)
        {
            case OrderSort.ByA: 
                sorter = (lines => lines.OrderBy(x => x.A)); break;
            case OrderSort.ByB:
                sorter = (lines => lines.OrderBy(x => x.B)); break;
    
            // and so on... a couple cases have several levels of ordering
        }
    
        bool requiresSplit = // a complicated condition
        if (requiresSplit)
        {
            var positives = unsorted.Where(x => x.Qty >= 0);
            var negatives = unsorted.Where(x => x.Qty <  0);
    
            return sorter(negatives).Concat(
                   new T[] { createLine.Invoke() }).Concat(
                   sorter(positives)).ToArray();
        }
        else
            return sorter(unsorted).ToArray();
    }
    

    So this sorts a group of items based on some criteria, and then it either returns the whole list sorted, or it breaks it in two, sorts both halves separately, and puts a separator in between them. Good luck doing this elegantly if you can't express the concept of "a way to sort something", which is what the delegate is for.

    EDIT: I guess Concat and OrderBy are 3.0-specific, but this is still the basic idea.

提交回复
热议问题