简体   繁体   English

组播代表

[英]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. C#中的所有委托都是多播委托,并且您可以具有通用委托,因此可以,您可以具有通用多播委托。 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 您应该使用Func委托而不是多委托

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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