问题描述
- C#新手,看到书上一个 关于foreach的例子,无法运行
- using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace foreachApp
{
class Program
{
public static void Main()
{IDictionary environment = Environment.GetEnvironmentVariables(); Console.WriteLine(""环境变量名t=t环境变量值""); //遍历environment中所有键值 foreach (string environment in environment.Keys) { Console.WriteLine(""{0}t=t{1}""environmentKeyenvironment [environmentKey].ToString()); } }}
}
大家帮忙看看哪里错误了,多谢
解决方案
IDictionary environment = Environment.GetEnvironmentVariables();
Console.WriteLine(""环境变量名t=t环境变量值"");
//遍历environment中所有键值
foreach (string key in environment.Keys)
{
Console.WriteLine(""{0}t=t{1}"" key environment[key].ToString()); }
解决方案二:
添加 using System.Collections;
解决方案三:
给你个完整的代码
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
class Program
{
static void Main(string[] args)
{
IDictionary environment = Environment.GetEnvironmentVariables();
Console.WriteLine(""环境变量名t=t环境变量值"");
//遍历environment中所有键值
foreach (DictionaryEntry de in environment)
{
Console.WriteLine(""{0}t=t{1}"" de.Key de.Value); } }}
}
解决方案四:
代码没问题,可以执行
完整代码:
using System;using System.Collections;class Sample { public static void Main() { Console.WriteLine(); Console.WriteLine(""GetEnvironmentVariables: ""); IDictionary environmentVariables = Environment.GetEnvironmentVariables(); foreach (DictionaryEntry de in environmentVariables) { Console.WriteLine("" {0} = {1}"" de.Key de.Value); } }}