Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get value from the object but its type is unreachable

Tags:

c#

reflection

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 ???

like image 362
jojo Avatar asked Jan 16 '10 00:01

jojo


2 Answers

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);
like image 192
Reed Copsey Avatar answered Sep 28 '22 18:09

Reed Copsey


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
like image 39
Marc Gravell Avatar answered Sep 28 '22 19:09

Marc Gravell