[英]How to access contents of Object If I don't know the structure in c#?
I have an object and I don't know its structure until runtime. 我有一个对象,直到运行时才知道其结构。 So is there any way to access data from the object ?
那么有什么方法可以从对象访问数据?
Thanks. 谢谢。
PS: I can't think of any other details to provide, please ask me if this isn't enough! PS:我想不出其他细节,请问我是否还不够!
Well, you can do with with reflection. 好吧,你可以做反射。 For example:
例如:
public static void ShowProperties(object o)
{
if (o == null)
{
Console.WriteLine("Null: no properties");
return;
}
Type type = o.GetType();
var properties = type.GetProperties(BindingFlags.Public
| BindingFlags.Instance);
// Potentially put more filtering in here
foreach (var property in properties.Where
(p => p.CanRead && p.GetIndexParameters().Length == 0))
{
Console.WriteLine("{0}: {1}", property.Name, property.GetValue(o, null));
}
}
Look at the Type API for ways to get methods, events, fields, nested types etc. 查看Type API,了解获取方法,事件,字段,嵌套类型等的方法。
看看反射
You can use reflection to determine what properties, methods, and fields an object has. 您可以使用反射来确定对象具有哪些属性,方法和字段。 take a look at the methods on the
Type
type 看一下
Type
类型的方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.