你好,以下是我总结的问题代码片段。
在第一段代码中,我在同一个类中声明了委托和事件,在代码2中,我将委托和事件分别声明在不同的类中。
代码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);
}
}
}
现在我有一个问题。这两个代码片段之间是否有任何区别(例如线程安全、性能)?