我有一个类,其中没有输入参数的公共(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/