.net 在C#中获取对象的所有属性值到数组中

oyjwcjzk  于 2023-06-07  发布在  .NET
关注(0)|答案(2)|浏览(245)

我试图将一个对象的所有字段值转换成数组。但问题是对象的字段可以有其他类型而不是字符串,但最终所有的值都应该是字符串。
比如说我们有一个红色的类

public class Apple
    {
        public string Name { get; set; }
        public string ReleasedYear { get; set; }
        public string SweetnessType { get; set; }
        public string Color { get; set; }
        public Stem StemType { get; set; }
    }

    public class Stem
    {
        public string name { get; set; }
        public string supplier { get; set; }
    }

    var apple = new Apple()
    {
        Name = "hodor", ReleasedYear = "1999",
        SweetnessType = "FruitLevel",
        Color = "Green",
        StemType = new Stem()
        {
            name = "stemar",
            supplier = "apple"
        }
    };

    // i want to get a result of ["hodor", "1999", "fruitLevel", "green", "stemar", "apple"]

如上所述,我想得到的结果是类“Apple”的所有属性的所有值。
我试过这个,它不起作用

private List<string> GetAllStringValuesFromObject(object model)
    {
        var result = new List<string>();

        PropertyInfo[] properties = model.GetType().GetProperties();

        foreach (PropertyInfo modelProp in properties)
        {
            if (modelProp.PropertyType.IsClass)
            {
                return GetAllStringValuesFromObject(modelProp);
            } 
            
            if (modelProp.PropertyType == typeof(string))
            {
                result.Add(modelProp.GetValue(model).ToString());
            }
        }

        return result;
    }

有没有一种注重表现的方法来做到这一点?有人能帮忙吗谢谢

5vf7fwbs

5vf7fwbs1#

让我们创建一个扩展类来扩展对象类型。然后,我们可以在任何对象类中使用下面的扩展,例如苹果,香蕉和橙子。;)

// Object Extensions
public static class ObjectExtensions
{
    public static List<string> GetStringValues(this object o)
    {
        var values = new List<string>(); // List of string property values
        var properties = o.GetType().GetProperties(); // Get all properties
        foreach (var property in properties) // Loop through properties
        {
            if (property.PropertyType == typeof(string)) // Check if property is string
                values.Add(property.GetValue(o).ToString()); // Add value to values
            else if (property.PropertyType.GetProperties().Length > 0) // Check if property has properties
            {
                var subValues = GetStringValues(property.GetValue(o)); // Recursion
                values.AddRange(subValues); // Add sub values to values
            }
        }
        return values;
    }
}

public class Apple
{
    public string Name { get; set; }
    public string ReleasedYear { get; set; }
    public string SweetnessType { get; set; }
    public string Color { get; set; }
    public Stem StemType { get; set; }
}

public class Stem
{
    public string name { get; set; }
    public string supplier { get; set; }
}

var apple = new Apple()
{
    Name = "hodor", ReleasedYear = "1999",
    SweetnessType = "FruitLevel",
    Color = "Green",
    StemType = new Stem()
    {
        name = "stemar",
        supplier = "apple"
    }
};

// Now you can simply call the method 'GetStringValues'
// that has been extended to all of your objects.
apple.GetStringValues();
l2osamch

l2osamch2#

好吧,这里有一个解决问题的方法:

private static List<string> GetAllStringValuesFromObject(object model)
{
    var result = new List<string>();

    PropertyInfo[] properties = model.GetType().GetProperties();

    foreach (PropertyInfo modelProp in properties)
    {
        if (modelProp.PropertyType == typeof(string))
        {
            result.Add(modelProp.GetValue(model).ToString());
        }
        else if (modelProp.PropertyType.IsClass)
        {
            // Pass in the value of the class, not the property itself, then add the result to the list.
            result.AddRange(GetAllStringValuesFromObject(modelProp.GetValue(model)));
        }
    }

    return result;
}

在你最初的GetAllStringValuesFromObject()中,你有一个关键的错误。如果迭代的modelProp是一个类,则传入PropertyInfo对象而不是属性的**Value。**此外,您将其设置为在该点返回,而不是添加到result列表,因此它将不返回任何内容。
希望这有助于澄清这个问题!

相关问题