C# 如何利用反射器获得阵列的长度
我有一个库和控制台程序,可以动态地获取这个库。在类的库中存在int数组。所以我可以在程序上,用反射器得到这个阵列吗?这是图书馆的代码:C# 如何利用反射器获得阵列的长度,c#,C#,我有一个库和控制台程序,可以动态地获取这个库。在类的库中存在int数组。所以我可以在程序上,用反射器得到这个阵列吗?这是图书馆的代码: public class Class1 { public int [] arrayInt; public Class1() { arrayInt = new int[5] {1,2,3,4,5}; } } 这是程序代码: Assembly asm = Assembly.LoadFile(@"C:\Test
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
不是属性而是成员变量,因此Class1.GetProperty(…)
返回null
备选方案1)使用GetMember
而不是GetProperty
MemberInfo List = Class1.GetMember("arrayInt");
public int[] ArrayInt
{
get { return arrayInt; }
}
备选方案2)在Class1
MemberInfo List = Class1.GetMember("arrayInt");
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.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};
}
}
如果您可以编辑问题,让我们知道引发了什么异常,这将非常有用。调用LINQ扩展方法
Count()
可能比计算长度要昂贵,或者不计算?对。但添加大括号是一个较小的更改;-)。但是,如果您查看源代码,那么额外的成本应该可以忽略不计:嗯,当它在整个集合中迭代时,它将是O(n),而不是O(1)。这对5个元素没有影响,但数组越长,影响就越大。@ThorstenDittmar实际上,如果您阅读Count()
的源代码,它会检查源代码是否是ICollection
,因此属性Count
可用,如果是,它只返回该属性。是的,我读到了-我只是不知道你可以将int[]
转换成ICollection
。我学到了一些新东西。谢谢(这仍然取决于ICollection.Count
实际上是如何由Array
实现的,但我认为这太过分了…)。