委托

委托让我们可以把函数引用保存在变量中。这就像在 C++ 中使用 typedef 保存函数指针一样。

委托使用关键字 delegate 声明。看看这个例子,你就能理解什么是委托:

例子:
代码:

delegate int Operation(int val1, int val2); 
public int Add(int val1, int val2) 
{ 
return val1 + val2; 
} 
public int Subtract (int val1, int val2) 
{ 
return val1- val2; 
} 
public void Perform() 
{ 
Operation Oper; 
Console.WriteLine("Enter + or - "); 
string optor = Console.ReadLine(); 
Console.WriteLine("Enter 2 operands"); 

string opnd1 = Console.ReadLine(); 
string opnd2 = Console.ReadLine(); 

int val1 = Convert.ToInt32 (opnd1); 
int val2 = Convert.ToInt32 (opnd2); 

if (optor == "+") 
Oper = new Operation(Add); 
else 
Oper = new Operation(Subtract); 

Console.WriteLine(" Result = {0}", Oper(val1, val2)); 
}

 

相关文章:

  • 2022-12-23
  • 2022-02-25
  • 2021-08-18
  • 2021-12-15
  • 2021-10-03
  • 2021-08-23
  • 2021-09-17
猜你喜欢
  • 2022-01-11
  • 2022-01-15
  • 2022-02-09
  • 2021-11-06
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案