我想遍历一个类并列出它的变量。 在SO上已经多次询问了这个问题,我已经尝试了所有答案。
由于某种原因,我无法获得解决方案。 当我运行下面的代码(该代码应该两次遍历该类,以尝试不同的方式)时,答案只是读取“ Test1”,这意味着它没有遍历该类。
有人知道为什么循环没有运行吗?
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)";
}
编辑:
基于Nico Schertler的评论表,他解释说我需要遍历字段而不是属性,我还尝试了以下相同的结果。
Type type = typeof(NodeHeaders);
foreach (var p in type.GetFields(System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic))
{
var v = p.GetValue(null); // static classes cannot be instanced, so use null...
Debug.WriteLine(v.ToString());
}
答案 0 :(得分:1)
由于您要访问的内容是公共静态字段,因此应使用
t.GetFields(BindingFlags.Static | BindingFlags.Public)
foreach (var field in typeof(NodeHeaders).GetFields(BindingFlags.Static | BindingFlags.Public))
{
// Get the name of the property
string fieldName = field.Name;
// Get the value of the property
object propertyValue = field.GetValue(null);
Console.WriteLine("test3");
Console.WriteLine(fieldName + ": " + (propertyValue == null ? "null" : propertyValue.ToString()));
}
这将正确访问字段值:
答案 1 :(得分:1)
这对您有用吗?
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)";
}
class Program
{
static void Main(string[] args)
{
DataGridViewNodes_CellValueChanged();
}
private static void DataGridViewNodes_CellValueChanged()
{
try
{
foreach (FieldInfo prop in typeof(NodeHeaders).GetFields())
{
object item = prop.GetValue(null);
Console.WriteLine($"{prop.Name} = {item.ToString()}");
}
}
catch (Exception ex)
{
throw;
}
Console.ReadKey();
}
}