Dea*_*bit 10 .net c# reflection
我想对我只能通过反射访问的索引属性进行迭代,
但是(并且我完全知道这可能是一个令人尴尬的简单回答,MSDN /谷歌失败= /)我找不到/想到除了递增计数器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 } ) );
}
}
}
Run Code Online (Sandbox Code Playgroud)
现在,这有一些问题...非常难看..解决方案..
如果它是多维的或者没有被整数索引,例如...
下面是我正在使用的测试代码,如果有人需要它,可以让它运行起来.如果有人有兴趣我正在制作一个自定义缓存系统而且.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() );
}
}
Run Code Online (Sandbox Code Playgroud)
在索引属性中具有连续索引号是您无法押注的。
索引属性不是数组。
反例:
Dictionary<int, bool> dictionary = new Dictionary<int, bool>();
dictionary[1] = true;
dictionary[5] = false;
Run Code Online (Sandbox Code Playgroud)
根据类型,您通常有其他方法来获取可能的索引值,在本例中为dictionary.Keys. 如果您的类型可能,我会按此顺序尝试
IEnumerable<T>该类型本身。IEnumerable<T>为每个索引属性实现一个相应的属性。如果您没有有效值的规范,也没有询问有效值是什么的方法,那么您就很不走运了。