Skip to main content
 首页 » 编程设计

c#之多播委托(delegate) : Different behavior when adding method references to a delegate in other methods

2024年02月13日14me-sa

我有以下声明委托(delegate)的代码:

delegate void EmployeeSalaryCalculated(int idEmp); 

我有这些简单的类:

    class Employee 
    { 
        public void CalculateSalary(int idEmp){} 
    } 
 
    class Payroll 
    { 
        public void EmpSalNotification(int idEmp) { }             
 
        public void SetMethod(ref EmployeeSalaryCalculated esc) 
        { 
            esc += this.EmpSalNotification; 
        }          
    } 
 
    class HR 
    { 
        public void EmpSalNotification(int idEmp) { }            
 
        public void SetMethod(ref EmployeeSalaryCalculated esc) 
        { 
            esc = this.EmpSalNotification; 
        } 
    } 

下面的按钮处理程序使用了上面的类:

private void btnStart_Click(object sender, EventArgs e) 
        {               
            Payroll payroll = new Payroll(); 
            HR hr = new HR();             
 
            EmployeeSalaryCalculated empSalCalculated = null; 
            empSalCalculated += payroll.EmpSalNotification; 
            empSalCalculated += hr.EmpSalNotification; 
 
            // This invokes both methods - fine.  
            // empSalCalculated.GetInvocationList() returns 2 
            empSalCalculated.Invoke(108); 
 
            EmployeeSalaryCalculated empSalCalculated2 = null; 
            payroll.SetMethod(ref empSalCalculated2); 
            hr.SetMethod(ref empSalCalculated2); 
 
            // This however, invokes only one method! 
            // empSalCalculated2.GetInvocationList() returns 1 
            empSalCalculated2.Invoke(108);     
        } 

尽管通过 ref 传递委托(delegate)对象 empSalCalculated2,它只执行一个函数,不像委托(delegate)对象 empSalCalculated 执行两个函数。

有什么想法吗?

请您参考如下方法:

问题出在HR.SetMethod这一行类:

esc = this.EmpSalNotification; 

此行覆盖任何值 esc以前有。所以,给定你打电话的顺序 SetMethod来自对象,empSalCalculated2仅包含来自 HR 的方法执行的实例。

要更正此问题,您可能需要重写 HR.SetMethod :

esc += this.EmpSalNotification; 

或颠倒SetMethod的顺序被称为:

hr.SetMethod(ref empSalCalculated2); 
payroll.SetMethod(ref empSalCalculated2);