我想itterate在索引属性,我只能访问通过反射,迭代(反射)
,但(我说这完全知道有可能是一个令人尴尬的答案很简单, MSDN /谷歌失败= /)除了PropertyInfo.GetValue(prop, counter)
增加计数器之外,我找不到/想到一种方法,直到TargetInvocationException
被抛出。
ALA:
foreach (PropertyInfo prop in obj.GetType().GetProperties())
{
if (prop.GetIndexParameters().Length > 0)
{
// get an integer count value, by incrementing a counter until the exception is thrown
int count = 0;
while (true)
{
try
{
prop.GetValue(obj, new object[] { count });
count++;
}
catch (TargetInvocationException) { break; }
}
for (int i = 0; i < count; i++)
{
// process the items value
process(prop.GetValue(obj, new object[] { i }));
}
}
}
现在,也有一些问题,这...非常难看.. ..解
,如果它是多维的或不被例如整数索引的.. 。
继承人我使用的尝试,并得到它的工作,如果有人需要它的测试代码。如果任何人感兴趣,我正在制作一个自定义缓存系统,而.Equals不会削减它。
static void Main()
{
object str = new String(("Hello, World").ToArray());
process(str);
Console.ReadKey();
}
static void process(object obj)
{
Type type = obj.GetType();
PropertyInfo[] properties = type.GetProperties();
// if this obj has sub properties, apply this process to those rather than this.
if (properties.Length > 0)
{
foreach (PropertyInfo prop in properties)
{
// if it's an indexed type, run for each
if (prop.GetIndexParameters().Length > 0)
{
// get an integer count value
// issues, what if it's not an integer index (Dictionary?), what if it's multi-dimensional?
// just need to be able to iterate through each value in the indexed property
int count = 0;
while (true)
{
try
{
prop.GetValue(obj, new object[] { count });
count++;
}
catch (TargetInvocationException) { break; }
}
for (int i = 0; i < count; i++)
{
process(prop.GetValue(obj, new object[] { i }));
}
}
else
{
// is normal type so.
process(prop.GetValue(obj, null));
}
}
}
else
{
// process to be applied to each property
Console.WriteLine("Property Value: {0}", obj.ToString());
}
}
什么`对象海峡=新的String的目的(( “你好,世界”)。ToArray的())`? – 2010-11-24 15:24:16
只是一个示例变量传递给我的函数...正在尝试定义一个字符串/字符串的不同方式,并将它留在一个尴尬的位...`object str =“Hello,World!”;``工作也一样。 – 2010-11-24 15:35:10
如果我有STRING键而不是整数,该怎么办?我不知道他们的名字。如何找到它们并使用? – Alexander 2017-12-07 20:51:47