Multicast Delegates must have a return type of void. Why?

前端 未结 3 1620
猫巷女王i
猫巷女王i 2021-01-05 03:22

Multicast Delegates must have a return type of void Otherwise it will throw an exception.

I want to know whats the reason behind it, what if multiple methods could h

3条回答
  •  萌比男神i
    2021-01-05 03:32

    in multicast the problem is that it override all values just print the last method value if it have return type,so you have to capture the return type of one by one,lets see the code below

     class Program
    {
        // i am going to add and subtract two num but i wanna get result in string the same thing you can do for int and what ever you want
          delegate string mydeledagte(int a,int b);
          delegate string d(int s, int t);
        static void Main(string[] args)
        {
            mydeledagte ab = new mydeledagte(ad);
            mydeledagte d= new mydeledagte(sub);
            mydeledagte multi = ab + d;
    
            foreach (mydeledagte individualMI in multi.GetInvocationList())
            {
                string retVal = individualMI(3, 5);
                Console.WriteLine("Output: " + retVal);
                Console.WriteLine("\n***developer of KUST***");
                Console.ReadKey();
            }
        }
        static string ad(int a, int b)
        {
    
            return (a + b).ToString();
    
        }
        static string sub(int a, int b)
        {
    
            return (a - b).ToString(); ;
        }
    }
    

提交回复
热议问题