代码之家  ›  专栏  ›  技术社区  ›  Eric Brown - Cal

.NET反射和数组

  •  1
  • Eric Brown - Cal  · 技术社区  · 15 年前

    我试图通过反射来获得一个一维数组属性的值

    我试过这样的方法:(为了清晰起见,试着把渔获量去掉)

    string[] fieldOrder;
    PropertyInfo fieldOrderColumn;
    
    fieldOrderColumn = targetType.GetProperty("OrderArray");
    
    if (fieldOrderColumn == null)
        throw new Exception(targetType.Name + " the OrderArray is null ");
    
    fieldOrder = (string[])fieldOrderColumn.GetValue(targetType, null);  //what should I use insted of this?
    

    显然,最后一行是错误的,并且试图获取一个非数组对象,我假设 快谷歌和我会在路上,但我找不到它。我不知道阵列在运行时的长度。

    任何提示、链接或帮助都将不胜感激。

    1 回复  |  直到 15 年前
        1
  •  3
  •   Marc Gravell    15 年前

    你需要通过 实例 类型为into的 GetValue . 如果是静态属性,则传递 null . 目前您正在通过 类型 . 我希望(大致)看到:

    Type targetType = obj.GetType();
    ...[snip]
    fieldOrder = (string[])fieldOrderColumn.GetValue(obj, null);
    

    请注意,如果您不确定数组的类型,可以使用 Array 而不是 string[] )或用于一维数组 IList 可能有用(并将处理数组、列表等):

    IList list = (IList)fieldOrderColumn.GetValue(obj, null);