Delegate Declaration

Hi I outlined my problem in the following code snippet. In the first code, I declared the delegate and event in the same class, and in Code 2 I declared the delegate and event in a 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. Are there any differences (e.g. thread safety, performance) between the two code snippets?

+3
source share
2 answers

The only difference seems to be in using a separate class. Thus, no: as long as methods and types are available, there are very few functional differences.

Action<string> , string void, , (object sender, SomeEventArgsClass e) ( SomeEventArgsClass:EventArgs, , EventHandler<T>)

+2

, , - ( ).

+2

Source: https://habr.com/ru/post/1779395/


All Articles