C# SoundPlayer - 应该是静态的还是基于实例的?

C# SoundPlayer - should be static or instance based?

我在 C# (WPF) 中使用 SoundPlayer class 一遍又一遍地播放相同的 .5s 音频(按键时)。每次用户按下自定义屏幕键盘按钮时,都会播放声音。

static SoundPlayer soundPlayer = null;
try
{
  soundPlayer = new SoundPlayer(@"c:\media\click.wav");
}
catch (Exception e)
{
  Logger.LogException(e);
}
// later on (usage)    
try
{
  soundPlayer?.Play();
}

任何人都可以就我是否应该将此 SoundPlayer obj 保持为静态或是否应该更改为基于实例提供一些指导? 谢谢!

我认为这没什么区别,因为无论哪种方式,它都只需要实例化一次——因为你正在播放同一个文件。

声明类型 SoundPlayer 的 class 成员,并使用初始化器实例化它。

static SoundPlayer soundPlayer = new SoundPlayer(@"c:\media\click.wav");

SoundPlayer soundPlayer = new SoundPlayer(@"c:\media\click.wav");

而且每当你需要播放声音时,你不需要对其执行空检查,只需调用

soundPlayer.Play(); 

对于资源处置,如果您不再使用它,请在实例上调用 Dispose 方法,例如,当 window 关闭时。

soundPlayer.Dispose();

Can anyone provide some guidance on if I should keep this SoundPlayer obj as static or if I should change to instance based?

这取决于 SoundPlayer 在您的应用程序中的使用位置和方式。如果您 will/can 总是使用相同的 SoundPlayer 实例而不以任何方式修改它,您可以在 class:

中将其定义为静态和只读字段
private static readonly SoundPlayer soundPlayer = new SoundPlayer(@"c:\media\click.wav");

那么不管你的class有多少运行时实例,都只会创建一个实例。 Play() 方法将使用新线程播放 .wav 文件。