如何从对象获取值,但其类型无法访问

joj*_*ojo 5 c# reflection

例如,在我当前的类中,有一个哈希表,

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

var b = t["key"];
Run Code Online (Sandbox Code Playgroud)

b的类型隐藏在我当前的类中,它是无法访问的,不是公共类类型.

但我想从b获得一个值,例如b有一个字段调用"ID",我需要从b获取ID.

无论如何我能得到它,反思???

Ree*_*sey 7

如果您不知道类型,那么您需要反思:

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);
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 6

在C#4.0中,这只是:

dynamic b = t["key"];
dynamic id = b.ID; // or int if you expect int
Run Code Online (Sandbox Code Playgroud)

除此以外; 反射:

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);
Run Code Online (Sandbox Code Playgroud)

另一种更简单的方法是让类型实现一个通用接口:

var b = (IFoo)t["key"];
var id = b.ID; // because ID defined on IFoo, which the object implements
Run Code Online (Sandbox Code Playgroud)