[英]Calling a static method of a class using reflection
我試圖通過反射調用靜態類方法並獲取其返回值,如下所示:
private SA GetData()
{
Type type = Type.GetType("SA010");
Object obj = Activator.CreateInstance(type);
MethodInfo methodInfo = type.GetMethod("GetSA");
return (SA)methodInfo.Invoke(obj, null);
}
這是我正在調用的類和方法:
public class SA010
{
public static SA GetSA()
{
//do stuff
return SA.
}
}
問題是我在'type'變量上收到一個空引用異常。 GetData()和SA010.GetSA()位於同一名稱空間中。
任何想法為什么我可能會得到這個錯誤,這與它是靜態的可能嗎?
您的主要問題是在使用GetType時需要指定SA010的完整命名空間。
Type type = Type.GetType("SomeNamespace.SA010");
但是,如果您沒有動態生成名稱,則更簡單的解決方案是使用typeof
,如果類型已在范圍內,則不需要整個命名空間。
Type type = typeof(SA010);
第二個問題,你將在修復類型后運行,如果方法是靜態的,你不創建它的實例,你只需為Invoke
調用的實例傳入null
。
private SA GetData()
{
Type type = typeof(SA010);
MethodInfo methodInfo = type.GetMethod("GetSA");
return (SA)methodInfo.Invoke(null, null);
}
嘗試使用
Type type = typeof(SA010);
代替
Type type = Type.GetType("SA010");
它對我有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.