gpt4 book ai didi

c# - 从未知对象获取属性和值

转载 作者:IT王子 更新时间:2023-10-29 03:32:41 26 4
gpt4 key购买 nike

在 PHP 世界中,我决定试一试 C#。我进行了搜索,但似乎找不到如何执行与此等效的操作的答案。

$object = new Object();

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

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

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

如有任何帮助,我们将不胜感激。

最佳答案

应该这样做:

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
}

关于c# - 从未知对象获取属性和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4144778/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com