Compatible delegate

1. compatible delegate type

delegate void D1();
delegate void D2(); 
D1 d1 = Method1;
D2 d2 = d1;

The following are permitted:

D2 d2 = newD2 (d1);

For the commission in the same target method it is to be treated as equal:

delegate void D();
...
D d1 = Method1;
D d2 = Method1;
Console.WriteLine (d1 == d2); // True

Similarly, for a multicast delegate, if it contains the same method and the same order, and are considered equal.

2. Parameter type compatibility

In OOP, any place using the parent class can be used instead of a subclass, the OOP idea equally effective parameters delegate. Such as:

delegate void StringAction(string s);class Program {
    static void Main() {
        StringAction sa = new StringAction(ActOnObject);
        sa("hello");
    }
    static void ActOnObject(object o) {
        Console.WriteLine(o); // hello
    }
}

3. The return type compatible

The same reason and argument types are compatible:

delegate object ObjectRetriever();class Program {
    static void Main() {
        ObjectRetriever o = new ObjectRetriever(RetriveString);
        object result = o();
        Console.WriteLine(result); // hello    }
    static string RetriveString() { return "hello"; }
}

 

Guess you like

Origin www.cnblogs.com/XiaoRuLiang/p/12422955.html