Advantages of using delegates?

前端 未结 14 1323
渐次进展
渐次进展 2020-12-13 11:39

I\'m looking to implement the Observer pattern in VB.NET or C# or some other first-class .NET language. I\'ve heard that delegates can be used for this, but can\'t figure ou

14条回答
  •  Happy的楠姐
    2020-12-13 12:13

    Here is an example that might help.

    There is an application that uses a large set of data. A feature is needed that allows the data to be filtered. 6 different filters can be specified.

    The immediate thought is to create 6 different methods that each return the data filtered. For example

    public Data FilterByAge(int age)

    public Data FilterBySize(int size)

    .... and so on.

    This is fine but is a very limited and produces rubbish code because it's closed for expansion.

    A better way is to have a single Filter method and to pass information on how the data should be filtered. This is where a delegate can be used. The delegate is a function that can be applied to the data in order to filter it.

    public Data Filter(Action filter)

    then the code to use this becomes

    Filter(data => data.age > 30);

    Filter(data => data.size = 19);

    The code data => blah blah becomes a delegate. The code becomes much more flexible and remains open.

提交回复
热议问题