簡體   English   中英

使用反射調用無參數的公共方法

[英]Invoke a public method with no parameters using reflection

我的用戶控件中有一個方法:

public string ControleIdContainer()
{
   string abc = "Hello";
   return abc;
}

現在,我想使用反射在我的Page上調用此方法。 我已經嘗試過了,但是沒有用:

DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("~/UserControls"));
FileInfo[] controlsInfo = dirInfo.GetFiles("*.ascx");
foreach (var item in controlsInfo)
{
    var customControl = LoadControl(string.Format("~/UserControls/{0}", item));
    var controlType = customControl.GetType();
    var controlClientScript = controlType.GetMethod("ControleIdContainer").Invoke(null,null);
}

出現錯誤的原因很多

1.原因1

您尚未將Invoke內部的類實例作為第一個參數。 該代碼應為

var controlClientScript = controlType.GetMethod("MethodName").Invoke(classInstance,null);

2.原因2

可以有多個與您的方法同名的方法(重載方法)。 在這種情況下,它將顯示以下錯誤。

發生類型為'System.Reflection.AmbiguousMatchException'的未處理異常。 找到不明確的匹配項。

因此,您需要指定您正在調用的方法沒有參數。 使用下面的代碼。

MethodInfo mInfo = classInstance.GetType().GetMethods().FirstOrDefault
                (method => method.Name == "MethodName"
                && method.GetParameters().Count() == 0);
mInfo.Invoke(classInstance, null);

3.原因3

如果使用Type.GetType來獲取類類型,則如果該類在另一個程序集中,則Type.GetType將為null。 在這種情況下,你必須通過環Assemblies 使用下面的代碼。

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

GetTheType方法在這里。 GetTheType的參數必須是完全限定名稱

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

MethodInfo.Invoke的第一個參數是您要在其上調用方法的實例。 customControl作為第一個參數而不是null傳遞,它應該可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM