[英]print all System.Environment information using System.Reflection
We have a little task to print in a console window all the variables of the Environment
class using reflection
, but how to do so I don't even have a clue.我们有一个小任务要在控制台窗口中使用reflection
打印Environment
类的所有变量,但如何做到这一点我什至不知道。 I am sorry if I've written anything wrong here, I'm new to C#
.如果我在这里写错了,我很抱歉,我是C#
新手。
Of course I could use this kind of code, but that is not what is required from me.当然我可以使用这种代码,但这不是我需要的。
string machineName = System.Environment.MachineName;
Console.WriteLine(machineName);
I searched Google so much and this is what I found, but I don't think this is what I need.我在谷歌上搜索了很多,这就是我找到的,但我认为这不是我需要的。 I don't even know what I need.我什至不知道我需要什么。
System.Reflection.Assembly info = typeof(System.Int32).Assembly;
System.Console.WriteLine(info);
Any suggestions, clues?有什么建议,线索吗?
You don't need reflection here你不需要在这里反思
foreach(DictionaryEntry e in System.Environment.GetEnvironmentVariables())
{
Console.WriteLine(e.Key + ":" + e.Value);
}
var compName = System.Environment.GetEnvironmentVariables()["COMPUTERNAME"];
Get the all public and static properties of Environment
using GetProperties
method, then display the name and the value of each property:使用GetProperties
方法获取Environment
的所有公共和静态属性,然后显示每个属性的名称和值:
var properties = typeof(Environment)
.GetProperties(BindingFlags.Public | BindingFlags.Static);
foreach(var prop in properties)
Console.WriteLine("{0} : {1}", prop.Name, prop.GetValue(null));
Although it's an old question, there is a neater possible answer based on the accepted answer, using Linq:虽然这是一个老问题,但使用 Linq,根据接受的答案有一个更简洁的可能答案:
IEnumerable<string> environmentVariables = Environment.GetEnvironmentVariables()
.Cast<DictionaryEntry>()
.Select(de => $"{de.Key}={de.Value}");
Console.WriteLine("Environment Variables: " + string.Join(Environment.NewLine, environmentVariables));
Or, a shorter version of the same code:或者,相同代码的较短版本:
Console.WriteLine("Environment Variables: " + string.Join(Environment.NewLine,
Environment.GetEnvironmentVariables()
.Cast<DictionaryEntry>()
.Select(de => $"{de.Key}={de.Value}")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.