Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/291.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在Singleton类上创建事件_C#_Compact Framework - Fatal编程技术网

C# 在Singleton类上创建事件

C# 在Singleton类上创建事件,c#,compact-framework,C#,Compact Framework,我有一个Windows Mobile 6.5(.net cf 3.5),它使用一个遵循以下模式的单例类: public sealed class Singleton { static readonly Singleton instance=new Singleton(); // Explicit static constructor to tell C# compiler // not to mark type as beforefieldinit static

我有一个Windows Mobile 6.5(.net cf 3.5),它使用一个遵循以下模式的单例类:

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;
        }
    }
}

我们班过去常常从中间驱动器收集GPS数据。我想要的是在singleton类上创建一个我可以订阅的事件?例如MyClass.Instance.LocationChanged+=

任何帮助都将不胜感激


标记

您应该能够像在任何课程上做事件一样完成此操作

public event Action<object, EventArgs> LocationChanged;

您可以在任何需要的地方启动OnLocationChanged方法,您所附加的事件将完成它们的工作。

您应该能够像在任何类上执行事件一样执行此操作

public event Action<object, EventArgs> LocationChanged;
您可以在任何需要的地方启动OnLocationChanged方法,您所附加的事件将完成它们的任务。

有什么问题

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
}
每当您想触发事件时,请调用
OnLocationChanged

有什么问题

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
}

每当您想启动事件时,请调用
OnLocationChanged

小心,订阅事件的任何代码都必须显式取消订阅。否则会导致内存泄漏。请小心,订阅事件的任何代码都必须显式取消订阅。如果不这样做,会导致内存泄漏。您不是缺少代理前面的“void”吗?您不是缺少代理前面的“void”吗?