c# - 如何调用无参方法?

标签 c# asp.net

我有一个类,其中没有输入参数的公共(public)方法。

 public partial class MyClass: System.Web.UI.MasterPage
   {

      public void HelloWorld() { 
       Console.WriteLine("Hello World "); 
      } 
    }

我想在我的另一个类中调用HelloWorld() 方法

public partial class ProductType_Showpt : System.Web.UI.Page
{
     protected void ChkChanged_Click(object sender, EventArgs e)
    {
          MyClass master =(MyClass) this.Master;   
          master.GetType().GetMethod("HelloWorld").Invoke(null, null);
    }
}

但是它抛出了这个异常

Object reference not set to an instance of an object.

最佳答案

这里您没有使用类作为 Invoke 中的第一个参数,即,您必须应用如下代码。

MyClass master= new MyClass();  
master.GetType().GetMethod("HelloWorld").Invoke(objMyClass, null);

现在,如果您有另一种带有某些参数的方法(重载方法),则可能会抛出错误。在这种情况下,您必须编写代码指定您需要调用没有参数的方法。

MyClass master= new MyClass();  
MethodInfo mInfo = master.GetType().GetMethods().FirstOrDefault
                (method => method.Name == "HelloWorld"
                && method.GetParameters().Count() == 0);
mInfo.Invoke(objMyClass, null);

现在如果你的类实例事先不知道你可以使用下面的代码。使用 Fully Qualified Name里面 Type.GetType

Type type = Type.GetType("YourNamespace.MyClass");
object objMyClass = Activator.CreateInstance(type);
MethodInfo mInfo = objMyClass.GetType().GetMethods().FirstOrDefault
                   (method => method.Name == "HelloWorld"
                    && method.GetParameters().Count() == 0);
mInfo.Invoke(objMyClass, null);

如果您的类实例事先未知,并且在另一个程序集中,Type.GetType 可能会返回 null。在这种情况下,对于上面的代码,而不是 Type.GetType,调用下面的方法

public Type GetTheType(string strFullyQualifiedName)
{
    Type type = Type.GetType(strFullyQualifiedName);
    if (type != null)
        return type;
    foreach (var asm in AppDomain.CurrentDomain.GetAssemblies())
    {
        type = asm.GetType(strFullyQualifiedName);
        if (type != null)
           return type;
    }
    return null;
}

然后调用

Type type = GetTheType("YourNamespace.MyClass");

关于c# - 如何调用无参方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15471896/

相关文章:

c# - 如何在代码中找到单元测试必须覆盖的地方

c# - "run text"标记在 XAML 中意味着什么?

javascript - Angular 在网页中没有显示任何内容,清楚地显示数组中的数据

c# - 获取唯一的线程 ID

asp.net - 当前不会命中断点。尚未为该文档加载任何符号

c# - 调用 format-number XPath 函数时,收到错误 : "Namespace Manager or XsltContext needed."

c# - 如果关联的 SqlConnection 将被处置,是否需要 SqlCommand.Dispose()?

c# - 如何处理对同一个套接字的读取和写入

javascript - 从 JavaScript 调用 ASP.NET 函数?

asp.net - 在 Visual Studio 2012 上预编译 Azure WebRole 发布(不通过 WebDeploy)