简体   繁体   中英

Delegate declaration

Hi I have summarized my problem in following code snippet. In the first code i have declared a delegate and event in the same class while in Code 2 i have declared delegate and event in separate class.

Code 1

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        delegate void Greeting(string s);
        event Greeting myEvent;
        void OnFire(string s)
        {
            if (myEvent != null)
                myEvent(s);

        }
        static void Main(string[] args)
        {
            Program obj = new Program();
            obj.myEvent += new Greeting(obj_myEvent);
            obj.OnFire("World");
        }

        static void obj_myEvent(string s)
        {
            Console.WriteLine("Hello " + s + "!");
        }
    }
}

code 2

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            DelegateDemo obj = new DelegateDemo();
            obj.myEvent+=new DelegateDemo.Greeting(obj_myEvent);
            obj.OnFire("World");
        }

        static void obj_myEvent(string s)
        {
            Console.WriteLine("Hello "+s +"!");
        }
    }
}

DelegateDemo.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    public class DelegateDemo
    {
       public delegate void Greeting(string s);
       public event Greeting myEvent;
       public void OnFire(string s)
        {
            if (myEvent != null)
                myEvent(s);

        }
    }
}

Now i have one question.Is there any diffrence (like thread safe ,performance) between these two code snippets?

The only difference seems to be the use of a separate class. So no: as long as the methods and types are accessible there is very little functional difference.

As a side note, you may want to consider Action<string> for a delegate that takes a string and returns void , but also note that events should generally follow the (object sender, SomeEventArgsClass e) pattern (where SomeEventArgsClass:EventArgs , perhaps also using EventHandler<T> )

实际上没有区别,但是你应该在类之外定义委托,因为委托是一个类(派生自Delegate)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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