使用c#反射来打印系统信息

本文关键字:系统 信息 打印 反射 使用 | 更新日期: 2023-09-27 18:13:15

我目前正在从头开始学习c#,我偶然发现了一个很难理解的主题,我想在控制台中打印出有关系统的信息。我读了关于Troelson的反射,并决定尝试一下,所以我在谷歌上找到了一个针对这个问题设计的windows窗体项目。我试着做一个类似的控制台应用程序,但是当我尝试打印时,我得到了一个未处理的异常。任何关于我如何做到这一点的建议或解释我做错了什么(我肯定有)将非常有帮助。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Data;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Reflection; 
namespace MachineInfo
{
    class Program
    {
        static void Main(string[] args)
        {
            Type propertytype = typeof(System.Windows.Forms.SystemInformation);
            PropertyInfo[] property = propertytype.GetProperties();
            string str; 
            for(int i=0; i<property.Length; i++ )
            {
                str = property[i].ToString();
                Type prop = typeof(System.Windows.Forms.SystemInformation);
                PropertyInfo innerproperty = prop.GetProperty(str);
                Console.WriteLine(innerproperty.ToString()); 
            }
        }
    }
}

使用c#反射来打印系统信息

你只需要:

for(int i=0; i<property.Length; i++ )
{
   Console.WriteLine("{0} : {1}",
                property[i].Name, 
                property[i].GetValue(null).ToString());
}

property[i].ToString();返回类型名称PropertyInfo,并且您试图获得一个不存在的名为PropertyInfo的属性。

如果你想获得静态属性别忘了指定BindingFlags

var flags = BindingFlags.Public | BindingFlags.Static;
PropertyInfo[] property = propertytype.GetProperties(flags);