从未知对象获取属性和值 [英] Get properties and values from unknown object

查看:19
本文介绍了从未知对象获取属性和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从 PHP 的世界开始,我决定尝试一下 C#.我进行了搜索,但似乎无法找到如何执行与此等效的答案.

From the world of PHP I have decided to give C# a go. I've had a search but can't seem to find the answer of how to do the equivalent to this.

$object = new Object();

$vars = get_class_vars(get_class($object));

foreach($vars as $var)
{
    doSomething($object->$var);
}

我基本上有一个对象的列表.该对象可以是三种不同类型中的一种,并且将具有一组公共属性.我希望能够获取该对象的属性列表,循环遍历它们,然后将它们写入文件.我认为这与 c# 反射有关,但这对我来说是全新的.

I basically have a List of an object. The object could be one of three different types and will have a set of public properties. I want to be able to get a list of the properties for the object, loop over them and then write them out to a file. I'm thinking this has something to do with c# reflection but it's all new to me.

任何帮助将不胜感激.

推荐答案

应该这样做:

Type myType = myObject.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());

foreach (PropertyInfo prop in props)
{
    object propValue = prop.GetValue(myObject, null);

    // Do something with propValue
}

这篇关于从未知对象获取属性和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆