如何获取类的属性的列表值?

问题描述 投票:0回答:1

我正在尝试遍历类的属性。在我得到定义为列表的属性之前,它工作正常。有没有一种简单的方法来处理此问题,因为我很确定,但是不幸的是我找不到解决方案。

当我遍历属性时,将显示特定类的正确值,但是只有它是单个值时,我才能获得任何列表值。如果我使用属性迭代,则属性列表将显示为

System.Collections.Generic.List`1 [System.Double]。

关于我的程序的一些背景知识。我动态创建类的List,并为其属性使用不同的值,因此为正确的类获取正确的值非常重要。

...

for(int j = 0; j<intensityList.Count; j++) {

                getIntensityofMode(intensityList[j]);
                Report.Log(ReportLevel.Info, "");
                Console.ReadLine();
            }
        }
        public void getIntensityofMode(HelpingClasses.IntensityData mode) {

            Type type = typeof(HelpingClasses.IntensityData);
            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                if(property.GetValue(mode, null) != null) {
                    Report.Log(ReportLevel.Info, property.Name + " = " + property.GetValue(mode, null));

                    if(property.PropertyType.IsGenericType &&
                       property.PropertyType.GetGenericTypeDefinition() == typeof(List<>)) {
                        Report.Log(ReportLevel.Info,"its a list");

                        foreach() 
//iterate through the property which is a list and holds several values
                        {
                        }
                    }
                } else {
                    Report.Log(ReportLevel.Info, property.Name + " = NaN");
                }
            }

所以我想,我只需要在foreach循环中写一行就可以得到我想要的内容,但我不知道如何处理。

//variables
        public string TxVoltagePulseMode{ get; set; }
        public double TxVoltagePulseDB{ get; set; }
        public double TxVoltagePulseVoltage{ get; set; }
        public List<double> TxFocusdepth{ get; set; }

因此,除了TxFocusdepth以外,其他所有代码都可以使用。

c# list loops foreach properties
1个回答
1
投票

您可以完全忽略它是通用列表这一事实,而只是将其视为非通用IList。

...

for(int j = 0; j<intensityList.Count; j++) {

            getIntensityofMode(intensityList[j]);
            Report.Log(ReportLevel.Info, "");
            Console.ReadLine();
        }
    }

public void getIntensityofMode(HelpingClasses.IntensityData mode) {

    Type type = typeof(HelpingClasses.IntensityData);
    PropertyInfo[] properties = type.GetProperties();
    foreach (PropertyInfo property in properties)
    {
        if(property.GetValue(mode, null) != null) {
            var value = property.GetValue(mode, null);
            // Test if it is IList and cast it if so
            if (value is IList e) {
                // Print the value of elements in the enumerable list
                foreach (var v in e) {
                    Report.Log(ReportLevel.Info, property.Name + " = " + v.ToString());
                }
            } else {
               Report.Log(ReportLevel.Info, property.Name + " = " + value);
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.