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

问题描述 投票:5回答:4

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

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

var b = t["key"];

b的类型对我当前的类是隐藏的,它是无法访问的,不是公共类类型。

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

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

c# reflection
4个回答
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);

6
投票

在C#4.0中,这只是:

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

除此以外;反射:

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);

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

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

0
投票

如果无法访问,您的意思是不是可公开实例化的类型?定义此类型的程序集的原因不存在,则无法获取对象本身,编译器将抛出错误。

所以,如果定义类型的程序集在那里,那么是的,你可以使用反射来实现它...


0
投票

试一试 :

 DataSet ds = (DataSet)OBJ;

 Int32 MiD  = Convert.ToInt32(ds.Tables[0].Rows[0]["MachineId"]);
© www.soinside.com 2019 - 2024. All rights reserved.