How can you loop over the properties of a class?

后端 未结 11 1574
温柔的废话
温柔的废话 2020-11-29 23:37

Is there a way in c# to loop over the properties of a class?

Basically I have a class that contains a large number of property\'s (it basically holds the results of

11条回答
  •  日久生厌
    2020-11-30 00:26

    string notes = "";
    
    Type typModelCls = trans.GetType(); //trans is the object name
    foreach (PropertyInfo prop in typModelCls.GetProperties())
    {
        notes = notes + prop.Name + " : " + prop.GetValue(trans, null) + ",";
    }
    notes = notes.Substring(0, notes.Length - 1);
    

    We can then write the notes string as a column to the log table or to a file. You have to use System.Reflection to use PropertyInfo

提交回复
热议问题