C# 是否可以列出所有字符串变量名和值
可以列出实例中的变量名及其值C# 是否可以列出所有字符串变量名和值,c#,reflection,field,C#,Reflection,Field,可以列出实例中的变量名及其值 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";
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");
}
}
公车
{
公共字符串颜色;
公共字符串模型;
公开制作;
}
受保护的无效页面加载(对象发送方、事件参数e)
{
//创建新实例
我的车=新车();
MyCar.Color=“红色”;
MyCar.Model=“日产”;
MyCar.Made=“日本”;
//这里有东西
foreach(MyCar中的MyCar变量)
{
写(“
变量名”+“XXX”+“变量值”);
}
}
这可以使用反射来完成。但是,如果您想枚举类中包含的任何内容,只需使用字典并枚举即可。您需要进行反射。
在这里,您可以看到一个类似的问题:
基于此,我认为您的案件将通过以下代码得到解决:
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;
}
private void Window\u已加载(对象发送方,路由目标)
{
FieldInfo[]myFieldInfo;
类型myType=类型(汽车);
myFieldInfo=myType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public);
字符串结果=@“Car类的字符串字段为:”;
对于(int i=0;i
类似这样的内容:
foreach (var prop in typeof(Car).GetProperties())
{
Response.Write(prop.Name + ": " + prop.GetValue(MyCar, null) ?? "(null)");
}
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));
}
}
}
试着这样做:
foreach (var prop in typeof(Car).GetProperties())
{
Response.Write(prop.Name + ": " + prop.GetValue(MyCar, null) ?? "(null)");
}
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));
}
}
}
然后应该是
GetFields()
,而不是GetProperties()
,这样才有效。请注意,使用公共字段通常是一种不好的做法。您应该改为使用属性。