是否可以列出我们所有的字符串变量名称和值
本文关键字:字符串 变量名 我们 是否 | 更新日期: 2023-09-27 17:55:10
可以列出实例中的变量名和它的值。
public class Car
{
public string Color;
public string Model;
public string Made;
}
protected void Page_Load(object sender, EventArgs e)
{
//Create new instance
Car MyCar = new Car();
MyCar.Color = "Red";
MyCar.Model = "NISSAN";
MyCar.Made = "Japan";
//SOMETHING HERE
foreach (MyCar Variable in MyCar)
{
Response.Write("<br/>Variable Name"+ "XXX"+ "Variable Value");
}
}
尝试这样的事情:
using System;
class Car
{
public string Color;
public string Model;
public string Made;
}
class Example
{
static void Main()
{
var car = new Car
{
Color = "Red",
Model = "NISSAN",
Made = "Japan"
};
foreach (var field in typeof(Car).GetFields())
{
Console.WriteLine("{0}: {1}", field.Name, field.GetValue(car));
}
}
}
你需要反射来做到这一点。在这里你可以看到一个类似的问题:如何获取我在类中的所有公共变量的列表?(C#)。
基于它,我认为您的情况将通过以下代码解决:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
FieldInfo[] myFieldInfo;
Type myType = typeof(Car);
myFieldInfo = myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
string result = @"The String fields of Car class are:";
for (int i = 0; i < myFieldInfo.Length; i++)
{
if (myFieldInfo[i].FieldType == typeof(String))
{
result += "'r'n" + myFieldInfo[i].Name;
}
}
MessageBox.Show(result);
}
public class Car
{
public string Color;
public string Model;
public string Made;
}
这可以使用反射来完成。但是,如果要枚举类中包含的任何内容,只需使用字典并枚举即可。
像这样:
foreach (var prop in typeof(Car).GetProperties())
{
Response.Write(prop.Name + ": " + prop.GetValue(MyCar, null) ?? "(null)");
}