动态运行方法不会抛出错误但没有发生任何事情

时间:2017-09-15 15:58:00

标签: c#

当我运行以下代码时,不会抛出任何错误,但正在调用的方法似乎不会运行。

string Class = Node.SelectSingleNode("class").InnerXml;
string[] Parameters = { Username, Password, Browser };

Type type = Type.GetType(Class);
Object obj = Activator.CreateInstance(type);
MethodInfo methodInfo = type.GetMethod("Case");

Thread userThread = new Thread(() => methodInfo.Invoke(obj, Parameters));
userThread.Start();

我已经检查过Class变量包含正确的字符串,它确实存在。我也运行了methodInfo.Invoke(...)而没有启动新线程,但我遇到了同样的问题。

修改

using System;
using System.Reflection;
using System.Xml;

namespace Example
{

    class MyClass
    {
        public static void Main(string[] args)
        {

            string Class = "OtherClass";
            string[] Parameters = { "User", "123", "IE" };

            Type type = Type.GetType(Class);
            Object obj = Activator.CreateInstance(type);
            MethodInfo methodInfo = type.GetMethod("MyFunction");

            methodInfo.Invoke(obj, Parameters)

        }
    }

    class OtherClass
    {

        public static void MyFunction(string[] Parameters)
        {
            Console.WriteLine(Parameters[0]);
        }

    }

}

我希望看到控制台打印出“用户”,但我得不到任何结果。调试代码后,由于“Object obj = ...”而出现错误。

由于以下代码仅输出“1.1”

Console.WriteLine("1");
Type type = Type.GetType(Class);
Console.WriteLine("1.1");
Object obj = Activator.CreateInstance(type);
Console.WriteLine("1.2");
MethodInfo methodInfo = type.GetMethod("Case");
Console.WriteLine("2");

1 个答案:

答案 0 :(得分:0)

你在这里弄错了几件事。我不知道为什么你说你没有任何例外。

  • 使用GetType()时,您必须提及完整的命名空间。
  • 调用需要object[]
  • 调用static方法时不需要创建实例(如果这样做,这不会引发错误)

public static void Main(string[] args)
{
    string classNameSpace = "Example.OtherClass";
    string[] Parameters = { "User", "123", "IE" };

    Type type = Type.GetType(classNameSpace);
    Object obj = Activator.CreateInstance(type);
    MethodInfo methodInfo = type.GetMethod("MyFunction");

    methodInfo.Invoke(null, new object[] { Parameters })
}