简体   繁体   English

委托方法属性

[英]Delegate Method Property

I made a simple delegate example to try to understand delegates. 我做了一个简单的委托示例,以试图了解委托。 Here is the code: 这是代码:

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("+++++++++++++++++++++++++++++++++++");
    }
}
}

and here is the output: 这是输出:

*******Simple Delegate Example*********
100
Method Name: Int32 Add(Int32, Int32)
1
Method Name: Int32 Add(Int32, Int32)
20
Method Name: Int32 Add(Int32, Int32)
+++++++++++++++++++++++++++++++++++ 

My Question: In the output, why does the .Method property return the same Name ('Add' in each case), yet the actual result returned is that of calling Multiply, Divide then Add? 我的问题:在输出中,为什么.Method属性返回相同的名称(在每种情况下为“ Add”),但是返回的实际结果是调用Multiply,Divide然后Add的结果?

Because you made a type in your Display method: 因为您是在Display方法中输入的,所以:

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

When it should be: 什么时候应该是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM