开发者

Delegates question - Basic

Alright, I have the following code: (copied from my book).

class MyDelegate
{
    public delegate void Func(string s);
    public void Show开发者_开发问答(string s)
    {
        Console.WriteLine("In MyD1: " + s);
    }
}
class Test
{
    static void Show(string s)
    {
        Console.WriteLine("In test: " + s);
    }
    static void Main(string[] args)
    {
        MyDelegate md = new MyDelegate();
        MyDelegate.Func f= new MyDelegate.Func(md.Show);
        MyDelegate.Func f1= new MyDelegate.Func(Show);
        f("hello");
        f1("Hello");
        f1 = f;
        f1("world");
    }
}

The output is: In MyD1: hello In TestShow Hello InMyD1: world

Now, I didn't understand why the last line of the output is in "InMyD1" . because f1 delegate is called and not f.

Thanks in advance.


You wrote f1 = f.

Therefore, you are calling f.


f1 = f;

This sets f1 to f thats why you have world instead of Hello


f1 is being reassigned the function reference of f. Likewise, if you just assigned it another function in place, such as:

f1 = s => Console.WriteLine("Another function: " + s);

You'd get other output.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜