【发布时间】:2019-10-29 16:41:02
【问题描述】:
我正在尝试遍历类的属性。 它工作正常,直到我得到一个定义为列表的属性。 有没有一种简单的方法来处理这个问题,因为我很确定,但是 不幸的是,我无法找到解决方案。
当我遍历属性时,将显示特定类的正确值,但只有当它是单个值时,我才能获得任何列表值。 如果我使用属性迭代,属性列表将显示为
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之外,所有代码都可以使用。
【问题讨论】:
-
检查属性是否为集合。如果是,则将该值提供给 for 或 foreach 循环。
-
是的,我知道步骤,但我不知道如何实现它..
-
因为我已经检查了它是否是一个列表,但我没有得到列表的值
标签: c# list loops foreach properties