-6
函數調用錯誤。我試圖用加法和乘法的運算程序,但它不工作就搞定了,我試圖召多功能我的代碼如下C#中的事件和代表#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace delegatEvents
{
delegate int number(int i);
class Program
{
public static event number variable;
static int no = 5;
public static int addnumber(int p)
{
no += p;
return no;
}
public static int multiply(int m)
{
no *= m;
return no;
}
public static int getnum()
{
return no;
}
static void Main(string[] args)
{
number p;
variable +=new number(addnumber);
variable += new number(multiply);
variable(3);
Console.WriteLine(" addition number is : {0}", getnum());
variable(2);
Console.WriteLine(" multiplication number is : {0}", getnum());
Console.ReadLine();
}
}
}
這是一個控制檯窗口的應用程序。
爲此使用事件沒有什麼意義。您正在訂閱這兩個事件,因此首先會發生添加,然後是每次調用「variable(n)'調用時的乘法。 – CodeCaster
點擊這裏 - [事件和代表簡化](http://www.codeproject.com/Articles/4773/Events-and-Delegates-Simplified) –
所以,你創建了組合委託'''變量'',變量(3)''' - >首先會加上no = 3 + no(5 + 3 = 8),然後再乘以no = 3 * no = 24.然後,在'''variable(2);' ''你首先添加no = 2 + no = 26,然後乘以no = 2 * no = 52.這就是爲什麼你會得到輸出24和52 – tym32167