在C#中动态检索索引属性的值

时间:2010-03-05 23:29:21

标签: c# reflection properties

我正在尝试为任何对象创建SortedList属性名称和值。下面的两个方法迭代一个对象的属性,将其各自的值存储在一个排序列表中(如果有更好的机制来完成这个,请推荐它。)

使用我当前的实现,我遇到了索引属性的问题。 Object.GetType Method提供了一种指定索引属性数组的机制,但我不确定如何利用它来获取属性的所有值。暂时我想将所有值连接成一个分隔的单个字符串。

private static SortedList<string, string> IterateObjProperties(object obj)
{
    IDictionaryEnumerator propEnumerator = ObjPropertyEnumerator(obj);
    SortedList<string, string> properties = new SortedList<string, string>();

    while (propEnumerator.MoveNext())
    {
        properties.Add(propEnumerator.Key.ToString(),
            propEnumerator.Value is String
            ? propEnumerator.Value.ToString() : String.Empty);
    }

    return properties;
}

private static IDictionaryEnumerator ObjPropertyEnumerator(object obj)
{
    Hashtable propertiesOfObj = new Hashtable();
    Type t = obj.GetType();
    PropertyInfo[] pis = t.GetProperties();

    foreach (PropertyInfo pi in pis)
    {
        if (pi.GetIndexParameters().Length == 0)
        {
            propertiesOfObj.Add(pi.Name,
              pi.GetValue(obj, Type.EmptyTypes).ToString());
        }
        else
        {
            // do something cool to store an index property
            // into a delimited string
        }
    }

    return propertiesOfObj.GetEnumerator();
}

3 个答案:

答案 0 :(得分:2)

一般来说,这是不可能做到的。索引器是一个接受参数的属性,它可以接受任何参数(适当的类型):不能保证会有一组有限的值:

public class DumbExample
{
  // What constitutes "all the values of" the DumbExample indexer?
  public string this[string s] { get { return s; } }
}

某些类可能提供一种方法来计算索引器(或索引器getter)的有效输入,例如: Dictionary<TKey,TValue>.Keys(当然,在这里,索引器集可以接受任何TKey,但是键至少可以获得getter的有效输入,在这种情况下你就是这样),List<T>.Count等。,但这将是针对特定类的。所以你的代码需要处理每个代码作为特例。

答案 1 :(得分:1)

无法知道类实例的索引属性的所有可能索引。索引器是一个接受参数的方法,因此与采用参数的任何其他方法一样,无法枚举所有可能的参数值组合。

答案 2 :(得分:0)

哇,这太可怕了。我希望有一种方法可以找到每个索引集并递归遍历每个索引的每个值。

我无法相信没有办法完成索引中设置的值。