[英]Call dynamic method from another class in visual c#
我嘗試從Visual Studio的另一個類中調用一個方法。 我使用了從數組到方法調用的字符串,但是該示例使用了簡單的字符串。
我讀了很多此類問題的答案,但仍然不知道出了什么問題。 沒有什么能解決我的問題。
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);
返回錯誤System.ArgumentNullException
請幫助我修復此腳本。
PS對不起,我的英語-)
由於type.GetType("Database")
返回null
而導致異常
您應該在參數中傳遞完全限定的名稱空間,如下所示
type.GetType("namespace.Database");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.