C# - Can someone tell me why and where I should us

2019-01-22 15:38发布

This question already has an answer here:

I think I understand the concept of a delegate in C# as a pointer to a method, but I cant find any good examples of where it would be a good idea to use them. What are some examples that are either significantly more elegant/better with delegates or cant be solved using other methods?

标签: c# delegates
12条回答
乱世女痞
2楼-- · 2019-01-22 16:14

there isn't really anything delgates will solve that can't be solved with other methods, but they provide a more elegant solution.

With delegates, any function can be used as long as it has the required parameters.

The alternative is often to use a kind of custom built event system in the program, creating extra work and more areas for bugs to creep in

查看更多
家丑人穷心不美
3楼-- · 2019-01-22 16:15

Events are the most obvious example. Compare how the observer pattern is implemented in Java (interfaces) and C# (delegates).

Also, a whole lot of the new C# 3 features (for example lambda expressions) are based on delegates and simplify their usage even further.

查看更多
淡お忘
4楼-- · 2019-01-22 16:18

Technically delegate is a reference type used to encapsulate a method with a specific signature and return type

查看更多
地球回转人心会变
5楼-- · 2019-01-22 16:22

I use them all the time with LINQ, especially with lambda expressions, to provide a function to evaluate a condition or return a selection. Also use them to provide a function that will compare two items for sorting. This latter is important for generic collections where the default sorting may or may not be appropriate.

   var query = collection.Where( c => c.Kind == ChosenKind )
                         .Select( c => new { Name = c.Name, Value = c.Value } )
                         .OrderBy( (a,b) => a.Name.CompareTo( b.Name ) );
查看更多
▲ chillily
6楼-- · 2019-01-22 16:24

The .NET 1.0 delegates:

this.myButton.Click += new EventHandler(this.MyMethod);

The .NET 2.0 delegates:

this.myOtherButton.Click += delegate {
    var res = PerformSomeAction();
    if(res > 5)
        PerformSomeOtherAction();
};

They seem pretty useful. How about:

new Thread(new ThreadStart(delegate {
    // do some worker-thread processing
})).Start();
查看更多
我想做一个坏孩纸
7楼-- · 2019-01-22 16:24

Outside of their role in events, which your probably familiar with if you've used winforms or asp.net, delegates are useful for making classes more flexible (e.g. the way they're used in LINQ).

Flexibility for "Finding" things is pretty common. You have a collection of things, and you want to provide a way to find things. Rather than guessing each way that someone might want to find things, you can now allow the caller to provide the algorithm so that they can search your collection however they see fit.

Here's a trivial code sample:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Delegates
{
    class Program
    {
        static void Main(string[] args)
        {
            Collection coll = new Collection(5);
            coll[0] = "This";
            coll[1] = "is";
            coll[2] = "a";
            coll[3] = "test";

            var result = coll.Find(x => x == "is");

            Console.WriteLine(result);

            result = coll.Find(x => x.StartsWith("te"));

            Console.WriteLine(result);

    }

}

public class Collection
{
    string[] _Items;

    public delegate bool FindDelegate(string FindParam);

    public Collection(int Size)
    {
        _Items = new string[Size];

    }

    public string this[int i]
    {
        get { return _Items[i]; }
        set { _Items[i] = value; }
    }

    public string Find(FindDelegate findDelegate)
    {
        foreach (string s in _Items)
        {
            if (findDelegate(s))
                return s;
        }
        return null;
    }

}
}

Output

is

test

查看更多
登录 后发表回答