如何在不键入属性名称的情况下遍历模型并打印

How to loop thru a model and print without typing the name of properties

我有一个填充了 20 个属性的模型,例如

public class SensorModel
{
    public string Trigger1 { get; set; }
    public string PathDoor1 { get; set; }
    public string PathDoor2 { get; set; }
    public string PathTrigger1 { get; set; }
    public string PathTrigger2 { get; set; }
    public string PathTrigger3 { get; set; }
    public string PathTrigger4 { get; set; }
    public string PathTrigger5 { get; set; }
    public string PathTrigger6 { get; set; }
    public string PathTrigger7 { get; set; }
    public string PathTrigger8 { get; set; }
}  

通过这样声明和设置它们的属性后,

SensorModel sensorsData = new SensorModel();

如何使用循环访问 sensorsData 的属性?

因为我想把所有的数据和DateTime一起记录到一个txt中,我发现手动访问是浪费时间。

有没有什么方法可以自动化,例如,使用循环并一个一个地访问它?

你可以使用反射来实现:

var obj = new SensorModel();
// ...

// Get all the properties of your class
var props = typeof(SensorModel).GetProperties();
foreach (var prop in props)
{
   // Get the "Get" method and invoke it
   var propValue = prop.GetGetMethod()?.Invoke(obj, null);
   // Do something with the value
   Console.Out.WriteLine("propValue = {0}", propValue);
}

您可以使用反射来实现您的目标:

var model = new SensorModel() {
    PathDoor1 = "Foo",
    PathDoor2 = "Foo2",
    PathTrigger1 = "Value of PT1",
    PathTrigger2 = "Value of PT2",
};

foreach(var value in model.GetTriggerValues()) {
    Console.WriteLine(value);
}


public class SensorModel
{

    public string Trigger1 { get; set; }
    public string PathDoor1 { get; set; }
    public string PathDoor2 { get; set; }
    public string PathTrigger1 { get; set; }
    public string PathTrigger2 { get; set; }
    /* ... */

    public IEnumerable<string> GetTriggerValues() {
        foreach(var prop in this.GetType().GetProperties().Where(x => x.Name.StartsWith("PathTrigger"))) {
            yield return (string)prop.GetValue(this, null);
        }
    }

}

此示例按名称过滤您的属性,如果您想要或需要不同的结果集,请修改或删除 where 子句。