Fra*_*k E 1 c# methods reference uwp
我尝试使用此代码示例构建一个测试应用程序
我定义了一个公共类,如下所示:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
从应用程序主页,然后我尝试调用:
public async void btnClick(object sender, RoutedEventArgs e)
{
await iSpeech.SpeakTextAsync("test speech", this.uiMediaElement);
}
Run Code Online (Sandbox Code Playgroud)
我继续得到
“非静态字段、方法或属性需要对象引用...”错误。
有人可以让我知道我做错了什么吗?
iSpeech是一个类,但您需要该类的一个实例才能使用非静态方法。
想想就好List<string>。你不能打电话
List<string>.Add("Hello");
Run Code Online (Sandbox Code Playgroud)
因为List<string>是一个类,就像创建对象的蓝图一样。(您会得到完全相同的错误。)您需要创建该类的实例才能使用它:
var myList = new List<string>();
myList.Add("Hello");
Run Code Online (Sandbox Code Playgroud)
所以在你的班级的情况下iSpeech,如果你声明
var mySpeechThing = new iSpeech();
Run Code Online (Sandbox Code Playgroud)
thenmySpeechThing将是一个表示 的实例的变量iSpeech,然后你可以做
await mySpeechThing.SpeakTextAsync("test speech", this.uiMediaElement);
Run Code Online (Sandbox Code Playgroud)
有时,一个类具有可以在不修改对象状态的情况下调用的方法(例如调用Adda 可以List<string>通过向其添加字符串来更改其状态。)我们将它们声明为static方法。它们属于类,而不属于类的实例。
为此,您可以将关键字static放在方法声明中,如下所示:
public static async Task SpeakTextAsync(string text, MediaElement mediaElement)
Run Code Online (Sandbox Code Playgroud)
然后你可以按照你想要的方式使用它。
static方法不能访问非静态类属性或方法。尽管有些人可能不同意,但通常最好不要使用static方法。他们不是邪恶的,但在你更熟悉之前,我会倾向于另一种方式。
| 归档时间: |
|
| 查看次数: |
3713 次 |
| 最近记录: |