委托方法属性

本文关键字:属性 方法 | 更新日期: 2023-09-27 18:29:01

我做了一个简单的委托示例来尝试理解委托。这是代码:

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?

委托方法属性

因为您在Display方法中创建了一个类型:

Console.WriteLine("Method Name: {0}", dobj.Method);              

应该在什么时候:

Console.WriteLine("Method Name: {0}", del.Method);