我想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