有很多原因讓錯誤
1原因1
您還沒有給出Invoke
內的類實例作爲第一個參數。該代碼應該是
var controlClientScript = controlType.GetMethod("MethodName").Invoke(classInstance,null);
。原因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
將是無效的。在這種情況下,您可以通過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
參數必須是一個Fully Qualified Name
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;
}
也許你應該使用一個接口,比如'IHaveControleIdContainer' - 那麼你可以做一個'as'投,測試空,並調用該方法。 – 2011-12-19 18:42:32
回聲@ default.kramer ...是的,總是避免反射,只要你可以。這應該是最後的手段。 – bobbymcr 2011-12-19 19:06:29