Create an event on Singleton Class
I have Windows Mobile 6.5 (.net cf 3.5) that uses a singleton class that follows this pattern:
public sealed class Singleton
{
static readonly Singleton instance=new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
My class was used to collect GPS data from a staging drive. I want to create an event in a singleton class that I can subscribe to? For example. MyClass.Instance.LocationChanged + = ...;
Any help would be greatly appreciated.
Mark
0
source to share
2 answers
What is the problem?
public sealed class Singleton
{
... your code ...
public delegate LocationChangedEventHandler(object sender, LocationChangedEventArgs ea);
public event LocationChangedEventHandler LocationChanged;
private void OnLocationChanged(/* args */)
{
if (LocationChanged != null)
LocationChanged(this, new LocationChangedEventArgs(/* args */);
}
}
public class LocationChangedEventArgs : EventArgs
{
// TODO: implement
}
Call OnLocationChanged
when you want to fire the event.
+3
source to share
You should just be able to do it like an event in any class.
public event Action<object, EventArgs> LocationChanged;
you can have a protected virtual method like:
protected virtual void OnLocationChanged(EventArgs args)
{
if(LocationChanged != null)
{
LocationChanged(this, args);
}
}
You can turn off your OnLocationChanged method when you need it too, and the event associated with it will do its job.
0
source to share