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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2075642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 23:17:29  来源:igfitidea点击:

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

c#reflection

提问by jojo

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.

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

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.

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

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

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

采纳答案by Reed Copsey

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

回答by Charles Bretana

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

因此,如果定义类型的程序集在那里,那么是的,您可以使用反射来获取它...

回答by Marc Gravell

In C# 4.0, this would just be:

在 C# 4.0 中,这将是:

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

回答by Hardeep Singh

Just Try :

你试一试 :

 DataSet ds = (DataSet)OBJ;

 Int32 MiD  = Convert.ToInt32(ds.Tables[0].Rows[0]["MachineId"]);