gpt4 book ai didi

c# - 使用反射循环遍历类变量

转载 作者:行者123 更新时间:2023-11-30 23:00:15 24 4
gpt4 key购买 nike

我想遍历一个类并列出它的变量。这已在 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());
}

最佳答案

因为你要访问的东西是公共(public)静态字段,你应该使用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()));
}

这将正确访问字段值:

enter image description here

关于c# - 使用反射循环遍历类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51696227/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com