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);
o开发者_JAVA技巧bj.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>
)
Actually there is no difference, but you should define delegates outside of classes since a delegate IS a class (deriving from from Delegate).
精彩评论