【问题标题】:C# how to load assembly with reflectionC#如何使用反射加载程序集
【发布时间】:2016-10-29 15:51:46
【问题描述】:

我正在尝试通过反射加载程序集System.Speech,以便我可以使用SpeakAsync 方法大声朗读一些文本。

这是我写的:

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

【问题讨论】:

标签: c# reflection .net-assembly


【解决方案1】:

您的代码包含错误,如果您指定了错误的命名空间(无论是通过反射还是没有它),您将无法使用类

您在这里使用了不正确的命名空间(这就是您收到空引用异常的原因):

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

以下是正确命名空间的示例:

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

更新1: 另一个注意事项。 invoke 返回一个提示,并且您不应该在异步方法工作时退出程序(当然,只有当您真的想听完语音时)。我在您的代码中添加了几行以等待语音完成:

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。我猜Mono 的实现存在一些问题。

【讨论】:

  • 我认为我不需要等待异步方法完成,如果我需要等待它完成,为什么它是异步的?这对我来说毫无意义。
  • @theonlygusti 确保您的程序集与您的应用程序位于同一文件夹中(您也可以指定完整路径)。
  • 它在同一个文件夹中
  • @theonlygusti 检查语言包
  • 我不知道语言包是什么
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-09
  • 1970-01-01
  • 2010-09-07
相关资源
最近更新 更多