Is it possible to list our all the string variable names and values out
Is is possible to list our the variable names from the instance and it value.
public class Car开发者_如何学JAVA
{
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");
}
}
Try something like this:
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));
}
}
}
You will need Reflection to do it. Here you can see a similar question: How do I get a list of all the public variables I have in a Class? (C#).
Based on it, I think your case will be solved by this code:
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;
}
This can be done using reflection. But if you want to enumerate whatever is contained within your class, you could simply use a dictionary and enumerate that.
Something like this:
foreach (var prop in typeof(Car).GetProperties())
{
Response.Write(prop.Name + ": " + prop.GetValue(MyCar, null) ?? "(null)");
}
精彩评论