我创建了一个简单的委托示例来尝试理解委托。这是代码:
namespace DelegateExample
{
public delegate int BinaryOp(int x, int y);
public class SimpleMath
{
public static int Add(int x, int y) { return x + y; }
public static int Subtract(int x, int y) { return x - y; }
public static int Multiply(int x, int y) { return x * y; }
public static int Divide(int x, int y) { return x / y; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("*******Simple Delegate Example************");
BinaryOp d = new BinaryOp(SimpleMath.Multiply);
d += SimpleMath.Divide;
d += SimpleMath.Add;
Display(d);
Console.ReadLine();
}
public static void Display(Delegate dobj)
{
foreach (BinaryOp del in dobj.GetInvocationList())
{
int ans = del.Invoke(10, 10);
Console.WriteLine(ans);
Console.WriteLine("Method Name: {0}", dobj.Method);
}
Console.WriteLine("+++++++++++++++++++++++++++++++++++");
}
}
}
这是输出:
*******Simple Delegate Example*********
100
Method Name: Int32 Add(Int32, Int32)
1
Method Name: Int32 Add(Int32, Int32)
20
Method Name: Int32 Add(Int32, Int32)
+++++++++++++++++++++++++++++++++++
我的问题: 在输出中,为什么.Method属性返回相同的Name(每种情况下都是'Add'),但返回的实际结果是调用Multiply,Divide然后Add?
答案 0 :(得分:1)
因为你在Display方法中输入了一个类型:
Console.WriteLine("Method Name: {0}", dobj.Method);
应该是:
Console.WriteLine("Method Name: {0}", del.Method);