我想要迭代一个只能通过反射访问到的索引属性,但是(我知道可能有非常简单的答案,但是MSDN/Google失败了=/)除了使用PropertyInfo.GetValue(prop, counter)
并增加计数器,直到抛出TargetInvocationException
之外,我找不到/想不到其他方法。
例如:
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() );
}
}
object str = new String(("Hello, World").ToArray())
的目的是什么? - Cheng Chenobject str ="Hello, World!";
同样可以正常工作。 - Dead.Rabit