[英]Throw exception when get error on reflection
我有圖書館和控制台程序。 該程序動態加載庫並獲取int數組。 但是程序拋出異常。 你能幫我解決嗎? 我的圖書館:
public class Class1
{
public int [] arrayInt;
public Class1()
{
arrayInt = new int[5] {1,2,3,4,5};
}
}
我的程序:
Assembly asm = Assembly.LoadFile(@"C:\TestLibrary.dll");
Type Class1 = asm.GetType("TestLibrary.Class1") as Type;
var testClass = Activator.CreateInstance(Class1);
MemberInfo[] List = Class1.GetMember("arrayInt");
foreach (FieldInfo field in List)
{
if (field.FieldType.IsArray)
{
int[] array = (int[])field.GetValue(null);//throw exception here
Console.WriteLine("Count of list. "+array.length);
foreach (var element in array)
Console.WriteLine(element.ToString());
break;
}
}
異常消息:
System.Reflection.TargetException:非靜態字段需要一個目標。 在Tets.Program.Main(String [] args)的System.Reflection.RtFieldInfo.GetValue(Object obj)的System.Reflection.RtFieldInfo.InternalGetValue(Object obj,StackCrawlMark&stackMark)處的System.Reflection.RtFieldInfo.CheckConsistency(Object target) )
PS:您可以修改代碼,而第一個數組不取自Loop嗎?
在循環的field變量中,您具有field的定義,當您想要獲取field的值時,應將對象傳遞給GetValue
方法,因此在代碼中,您需要編寫如下內容
int[] array = (int[])field.GetValue(testClass);
由於此Field實例字段(非靜態),您需要將實例傳遞給GetValue ()方法。
int[] array = (int[])field.GetValue(testClass);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.