2016-10-29 27 views
-4

我試圖通過反射加載程序集,System.Speech,以便我可以使用SpeakAsync方法朗讀一些文本。C#如何通過反射加載程序集

我寫了這個:

System.Reflection.Assembly assembly = System.Reflection.Assembly.LoadFrom("System.Speech.dll"); 
System.Type type = assembly.GetType("System.Speech.SpeechSynthesizer"); 
var methodinfo = type.GetMethod("SpeakAsync", new System.Type[] {typeof(string)}); 
if (methodinfo == null) throw new System.Exception("No methodinfo."); 

object[] speechparameters = new object[1]; 
speechparameters[0] = GetVerbatim(text); // returns something like "+100" 

var o = System.Activator.CreateInstance(type); 
methodinfo.Invoke(o, speechparameters); 

但得到的錯誤

System.NullReferenceException: Object reference not set to an instance of an object 
+0

這看起來像一個副本: http://stackoverflow.com/questions/14479074/c-sharp-reflection-load-assembly-and-invoke-a-method-if-it-exists 也許這是部分問題太:http://stackoverflow.com/questions/6049332/i-cant-find-system-speech – Marksl

+0

@Marksl我看着第一個問題,以獲得我現在的代碼,但你可以見上面,它不工作,所以... – theonlygusti

+0

我發誓,有人真的恨我,只是低估了我所有的問題。嚴重的是,這有什麼問題? – theonlygusti

回答

0

你的代碼中包含的錯誤,你可以用類,如果你指定了不正確的命名空間無法正常工作(既不是通過反射,也沒有它)

您在此處使用不正確的命名空間(這就是爲什麼你收到空引用除外):

System.Type type = assembly.GetType("System.Speech.SpeechSynthesizer");//type == null 

這裏是例子正確的命名空間:

System.Type type = assembly.GetType("System.Speech.Synthesis.SpeechSynthesizer"); 

UPDATE1: 另一個需要注意的。 invoke會返回一個提示,並且在異步方法正在工作時不應該退出程序(當然,只有當您真的想要聽話時才結束)。我添加幾行代碼要等到speach將完成:

internal class Program 
{ 
    private static void Main(string[] args) 
    { 
     var assembly = Assembly.LoadFrom("System.Speech.dll"); 
     var type = assembly.GetType("System.Speech.Synthesis.SpeechSynthesizer"); 
     var methodinfo = type.GetMethod("SpeakAsync", new[] {typeof(string)}); 
     if (methodinfo == null) throw new Exception("No methodinfo."); 

     var speechparameters = new object[1]; 
     speechparameters[0] = "+100"; // returns something like "+100" 

     var o = Activator.CreateInstance(type); 
     var prompt = (Prompt) methodinfo.Invoke(o, speechparameters); 

     while (!prompt.IsCompleted) 
     { 
      Task.Delay(500).Wait(); 
     } 
    } 
} 

更新2

請確保您有正確的語言包。 MSDN

更新3 如果使用單聲道,儘量確保此功能應該Mono作品。我認爲Mono實現有一些問題。

+0

做到了這一點,得到了一個新的錯誤:http://pastebin.com/iPdQyPQU – theonlygusti

+0

@theonlygusti看看update2 – burzhuy

+0

我不認爲我需要等待異步方法完成,爲什麼它是異步的,如果我需要等待它完成?這對我來說毫無意義。 – theonlygusti