简体   繁体   中英

Multicast Delegates

Can we use multicast delegates using Generics? Please explain with the below code how it is possible.

delegate string multidelegate<T1,T2>(T1 a,T2 b);

class mylogic
{
   public void Method1(int a, int b)
    {
        Console.WriteLine("This is Method1 where value of multiplication is {0}",a*b);
    }

    public void Method2(double a, double b)
    {
        Console.WriteLine("This is Method2 where the value of multiplication is {0}",a*b);
    }
}

class Program
{
    static void Main(string[] args)
    {
        multidelegate<int,int> del = new multidelegate<int,int>(new mylogic().Method1).Tostring();
        del += Convert.ToString(new multidelegate<double,double>(new mylogic().Method2).Tostring());

        del(32,51);
    }
}

All delegates in C# are multicast delegates, and you can have generic delegates, so yes, you can have generic multicast delegates. All generic delegates are generic multicast delegates.

However, you cannot combine two instances of a generic delegate if they have different generic arguments. You can only combine instances of the same delegate with the same generic type arguments. This should make sense as the whole point of being able to combine delegates is that they need to have the same contract; they need to accept the same arguments and output the same type of output. If the generic arguments are different, that wouldn't be the case.

Can we use multicast delegates using Generics? Yes Multicasting delegates is the action of calling multiple subscribers through your delegate and return the result of the call to the last subscriber.

You should use Func delegate instead your multidelegate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM