2016-07-16 46 views
0

我尝试使用这个代码exampleC#是所必需的非静态字段,方法或属性的对象引用 - 语音合成

我定义一个公共类按下面构建一个测试应用程式:

public class iSpeech 
{ 
    // Performs synthesis 
    public async Task<IRandomAccessStream> SynthesizeTextToSpeechAsync(string text) 
    { 
     IRandomAccessStream stream = null; 
     using (SpeechSynthesizer synthesizer = new SpeechSynthesizer()) 
     { 
      VoiceInformation voiceInfo = 
       (
       from voice in SpeechSynthesizer.AllVoices 
       where voice.Gender == VoiceGender.Male 
       select voice 
      ).FirstOrDefault() ?? SpeechSynthesizer.DefaultVoice; 

      synthesizer.Voice = voiceInfo; 
      stream = await synthesizer.SynthesizeTextToStreamAsync(text); 
     } 
     return (stream); 
    } 

    // Build audio stream 
    public async Task SpeakTextAsync(string text, MediaElement mediaElement) 
    { 
     IRandomAccessStream stream = await this.SynthesizeTextToSpeechAsync(text); 
     await mediaElement.PlayStreamAsync(stream, true); 
    } 
} 

从应用程序的主网页,我又试图以拨打:

public async void btnClick(object sender, RoutedEventArgs e) 
    { 
     await iSpeech.SpeakTextAsync("test speech", this.uiMediaElement); 
    } 

我不断获取

“非静态字段,方法或属性...”需要对象引用错误。

有人请让我知道我做错了吗?

回答

3

iSpeech是一类,但你需要一个类的实例为了使用非静态方法。

想想它像List<string>。您不能拨打电话

List<string>.Add("Hello"); 

因为List<string>是类,就像创建对象的蓝图一样。 (你会得到确切的同样的错误。)你需要创建一个类的实例来使用它:

var myList = new List<string>(); 
myList.Add("Hello"); 

所以在你的类,iSpeech,如果你宣布

var mySpeechThing = new iSpeech(); 
的情况下,

然后mySpeechThing将较iSpeech一个实例变量,那么你可以做

await mySpeechThing.SpeakTextAsync("test speech", this.uiMediaElement); 

有时,一个类有可能是方法在不修改对象状态的情况下调用(例如通过在List<string>上调用Add通过向其添加字符串来更改其状态)。我们将它们声明为static方法。他们属于班级,而不属于班级的实例。

要做到这一点,你就会把关键字static在这样的方法声明:

public static async Task SpeakTextAsync(string text, MediaElement mediaElement) 

然后,你可以使用它,你试图方式。

static方法不能访问非静态类属性或方法。虽然有些人可能不同意,但最好不要使用static方法。他们不是邪恶的,但直到你更熟悉我会倾向于另一种方式。

+0

非常感谢Scott,这正是我所需要的。 var mySpeechThing = new iSpeech();等待mySpeechThing.SpeakTextAsync(“测试语音”,this.uiMediaElement); –

+0

不客气!头发拆分细节:为了使代码更加一致可读,建议让类以大写字母开头。除非它是以“I”开头的单词,否则通常将接口用于使用“I”表示类型名称。 (但显然没有规则。) –

+0

再次感谢:) –

1

您在Method SpeakTextAsync中缺少“static”关键字。

public static async Task SpeakTextAsync(string text, MediaElement mediaElement) 
{ 
    IRandomAccessStream stream = await this.SynthesizeTextToSpeechAsync(text); 
    await mediaElement.PlayStreamAsync(stream, true); 
} 
+0

感谢您的回复Alan。不幸的是,这个.SynthesizeTextToSpeechAsync不能是静态的并且返回错误。下一个答复解决了它。 –

相关问题