使用C#的反射机制读取类的字段名称及值

using System.Windows.Forms;
using System.Reflection;

foreach (FieldInfo fi in typeof(SystemInformation).GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
{
Console.WriteLine(fi.Name);
Console.WriteLine(fi.GetValue(fi.Name));
}

注:System.Reflection.FieldInfo :发现字段特性并提供对字段元数据的访问权。
System.Windows.Forms.SystemInformation:提供当前系统环境的有关信息。

例:

 1     class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             Console.WriteLine("名-->值");
 6             foreach (FieldInfo fi in typeof(ClassTest).GetFields(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))
 7             {
 8                 Console.WriteLine("{0}-->{1}", fi.Name, fi.GetValue(fi.Name));
 9             }
10             Console.ReadKey();
11         }
12     }
13     public class ClassTest
14     {
15         private static string a = "123";
16         public string A
17         {
18             get { return a; }
19             set { a = value; }
20         }
21 
22         private static int i = 21;
23         public int I
24         {
25             get { return i; }
26             set { i = value; }
27         }
28 
29         private static bool b = true;
30         public bool B
31         {
32             get { return b; }
33             set { b = value; }
34         }
35     }
原文地址:https://www.cnblogs.com/xifengyeluo/p/6122160.html