tags:

views:

59

answers:

3

For instance, in my current class, there is a hashtable,

Hashtable t = GetHashable(); //get from somewhere.

var b = t["key"];

the type of b is hidden from my current class, it is unreachable, not a public class type.

but i want to get a value from b, for example b has a field call "ID", i need to get the ID from b.

is there anyway i can get it, reflection ???

A: 

By unreachable, you mean not a publically instantiable type? Cause if the assembly that defines this type is not there, then the object itself could not be fetched, the compiler would throw an error.

So, if the assembly defining the type is there, then yes you can use reflection to get at it...

Charles Bretana
+3  A: 

If you don't know the type, then you'll need reflection:

object b = t["key"];
Type typeB = b.GetType();

// If ID is a property
object value = typeB.GetProperty("ID").GetValue(b, null);

// If ID is a field
object value = typeB.GetField("ID").GetValue(b);
Reed Copsey
what is a field? what is a properties???
shrimpy
(replied to that question on the top post)
Marc Gravell
how about the properties is sepcify as internal..your method didn`t work for it
shrimpy
If it's internal (or private/protected), use: typeB.GetProperty("ID", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(b, null); (For details, see: http://msdn.microsoft.com/en-us/library/zy0d4103.aspx)
Reed Copsey
@Marc Gravell: Thanks for replying before I saw the comment ;)
Reed Copsey
+3  A: 

In C# 4.0, this would just be:

dynamic b = t["key"];
dynamic id = b.ID; // or int if you expect int

Otherwise; reflection:

object b = t["key"];
// note I assume property here:
object id1 = b.GetType().GetProperty("ID").GetValue(b, null);
// or for a field:
object id2 = b.GetType().GetField("ID").GetValue(b);

Another easier approach is to have the type implement a common interface:

var b = (IFoo)t["key"];
var id = b.ID; // because ID defined on IFoo, which the object implements
Marc Gravell