在 Visual C# 中从另一个 class 调用动态方法

Call dynamic method from another class in visual c#

我尝试调用 visual studio 中另一个 class 的方法。我使用数组中的字符串进行方法调用,但该示例使用简单的字符串。

看了很多此类问题的答案,还是不知道哪里出了问题。没有什么能解决我的问题。

部分form1.cs

public partial class Form1 : Form
{

    private void Form1_Load(object sender, EventArgs e)
    {

        Type type = Type.GetType("Database");
        object instance = Activator.CreateInstance(type);
        MethodInfo theMethod = type.GetMethod("MyMethod");
        theMethod.Invoke(instance, null);

    }
}

部分Database.cs

public class Database
{
    public void MyMethod()
    {
        MessageBox.Show("Test2");
    }
}

无法执行脚本,因为行 object instance = Activator.CreateInstance(type); return 错误 System.ArgumentNullException

请帮我修复这个脚本。

P.S。对不起我的英语 -)

异常是因为type.GetType("Database") returns null

您应该像下面这样在参数中传递完全限定的命名空间

type.GetType("namespace.Database");