I want to loop through a Class and list it's Variables. This has been asked multiple times on SO, and I have tried all the answers.
For some reason I can't get the solutions to work. When I run the code below (which should loop through the class twice, just to try different ways), the answer just reads 'Test1' meaning that it hasn't looped through the class.
Does anyone know why the loops aren't running?
public partial class Tables : Form
{
private void dataGridViewNodes_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
Debug.WriteLine("test1");
//Simple Test
foreach (PropertyInfo prop in typeof(NodeHeaders).GetProperties())
{
Debug.WriteLine("test2");
Debug.WriteLine(prop.Name);
}
//the above should have looped through the class so let's try again
var nodeHeaders = new NodeHeaders();
Type t = nodeHeaders.GetType();
string fieldName;
object propertyValue;
// Use each property of the object passed in
foreach (PropertyInfo pi in t.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
// Get the name of the property
fieldName = pi.Name;
// Get the value of the property
propertyValue = pi.GetValue(nodeHeaders, null);
Debug.WriteLine("test3");
Debug.WriteLine(fieldName + ": " + (propertyValue == null ? "null" : propertyValue.ToString()));
}
}
}
public class NodeHeaders
{
public static string node_name = "Conduit Name";
public static string x = "Easting (m)";
public static string y = "Northing (m)";
public static string z_cover = "Cover Level (m)";
}
Aucun commentaire:
Enregistrer un commentaire