Reflection?

  • Thread starter Thread starter farseer
  • Start date Start date
F

farseer

Hi,
suppose i have an array of two different class types.
TypeA[] array1;
TypeB[] array2;

Now supposing both TypeA and TypeB contain a property called "id"
(they, do not inherit from a common base class or interface, that just
happens to be the method name).
I'd like to be able to pass either array to a method and call the "id"
method. for instance,

...
processArray( array1 ); //array contain objects of TypeA
processArray( array2 ); //array contain objects of TypeB
...

public void processArray( Object[] arr )
{
for( int i = 0; i < arr.Length; i++ )
{
System.Console.WriteLine("Value: " + arr[ i ].id);
}
}


How can i do this?
 
Hi farseer,
you could do something like the following:

static void Main(string[] args)
{
Type t1 = typeof(TypeA);
Type t2 = typeof(TypeB);

TypeA a = new TypeA();
TypeB b = new TypeB();

int aId = (int)t1.InvokeMember("id",

System.Reflection.BindingFlags.GetProperty,
null,
a,
null);

int bId = (int)t2.InvokeMember("id",

System.Reflection.BindingFlags.GetProperty,
null,
b,
null);
}
}

class TypeA
{
public int id
{
get
{
return 1;
}
}
}

public class TypeB
{
public int id
{
get
{
return 2;
}
}
}


Hope that helps
Mark R Dawson
http://www.markdawson.org
 
Back
Top