【问题标题】:print all System.Environment information using System.Reflection使用 System.Reflection 打印所有 System.Environment 信息
【发布时间】:2014-04-20 20:34:23
【问题描述】:

我们有一个小任务要在控制台窗口中使用reflection 打印Environment 类的所有变量,但我什至不知道该怎么做。如果我在这里写错了,我很抱歉,我是C#的新手。

我当然可以使用这种代码,但这不是我需要的。

string machineName = System.Environment.MachineName;
Console.WriteLine(machineName);

我在 Google 上搜索了很多,这就是我找到的,但我认为这不是我需要的。我什至不知道我需要什么。

System.Reflection.Assembly info = typeof(System.Int32).Assembly;
System.Console.WriteLine(info);

有什么建议、线索吗?

【问题讨论】:

  • typeof(Environment)的成员

标签: c# environment-variables console-application system.reflection


【解决方案1】:

这里不需要反思

foreach(DictionaryEntry e in System.Environment.GetEnvironmentVariables())
{
    Console.WriteLine(e.Key  + ":" + e.Value);
}

var compName = System.Environment.GetEnvironmentVariables()["COMPUTERNAME"];

【讨论】:

    【解决方案2】:

    使用GetProperties方法获取Environment的所有publicstatic属性,然后显示每个属性的名称和值:

    var properties = typeof(Environment)
                    .GetProperties(BindingFlags.Public | BindingFlags.Static);
    
    foreach(var prop in properties)
       Console.WriteLine("{0} : {1}", prop.Name, prop.GetValue(null));
    

    【讨论】:

    • 这里不需要反思。更好地依赖公共 API GetEnvironmentVariables
    猜你喜欢
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 2021-02-19
    相关资源
    最近更新 更多