簡體   English   中英

如何使用反射器獲取數組的長度

[英]How to get Length of array using reflector

我有庫和控制台程序,可以動態獲取該庫。 在類上的庫中存在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);                
    PropertyInfo List = Class1.GetProperty("arrayInt");
    int[] arrayTest = (int[])List.GetValue(testClass, null);//throw exception here
    Console.WriteLine("Length of array: "+arrayTest.Count);
    Console.WriteLine("First element: "+arrayTest[0]);

您會因為public int[] arrayInt;而獲得異常public int[] arrayInt; 不是屬性而是成員變量,因此Class1.GetProperty(...)返回null

替代方法1)使用GetMember代替GetProperty

MemberInfo List = Class1.GetMember("arrayInt");

備選方案2)在Class1聲明一個屬性

public int[] ArrayInt 
{ 
    get { return arrayInt;  }
}

並將反射代碼更改為:

PropertyInfo List = Class1.GetProperty("ArrayInt");

另外,請注意,您的代碼甚至不應該編譯,因為數組沒有Count屬性,而只有Length屬性。 以下行應給出編譯錯誤:

Console.WriteLine("Length of array: "+arrayTest.Count);

並應閱讀

Console.WriteLine("Length of array: "+arrayTest.Length);

采用

Class1.GetMember("arrayInt");

的安裝

Class1.GetProperty("arrayInt");

您正在原始類中創建一個字段,但將其反映為屬性!

public class Class1
{
    public int [] arrayInt {get;set;} // <-- now this is a property
    public Class1()
    {
        arrayInt = new int[5] {1,2,3,4,5};
    }
}

僅在arrayTest.Count之后添加()

Assembly asm = Assembly.LoadFile(@"C:\TestLibrary.dll");
Type Class1 = asm.GetType("TestLibrary.Class1") as Type;
var testClass = Activator.CreateInstance(Class1);                
PropertyInfo List = Class1.GetProperty("arrayInt"); // <!-- here you are looking for a property!
int[] arrayTest = (int[])List.GetValue(testClass, null);//throw exception here
Console.WriteLine("Length of array: "+arrayTest.Count());
Console.WriteLine("First element: "+arrayTest[0]);

暫無
暫無

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

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