8

I would like to know how do I declare/initialize a dictionary ? The below one gives error.

Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>()
{
  {"tab1", MyList }
};

List <string> MyList = new List<string>() { "1" };

The error is: A field initializer cannot reference the non-static field, method, or property MyList. It is not List declaration coming in front or later after dictionary.

4

3 に答える 3

9
Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>()
{
    {"tab1", new List<string> { "1" } },
    {"tab2", new List<string> { "1","2","3" } },
    {"tab3", new List<string> { "one","two" } }
};
于 2014-03-06T07:59:27.917 に答える
6

As Scott Chamberlain said in his answer:

If these are non static field definitions you can not use the field initializers like that, you must put the data in the constructor.

class MyClass
{
    Dictionary<string, List<string>> myD;        
    List <string> MyList;

    public MyClass()
    {
        MyList = new List<string>() { "1" };
        myD = new Dictionary<string, List<string>>()
        {
          {"tab1", MyList }
        };
    }
}

Additionally for Static field

private static List<string> MyList = new List<string>()
{    
   "1"
};

private static Dictionary<string, List<string>> myD = new Dictionary<string, List<string>>()
{
    {"tab1", MyList }

};
于 2013-01-23T04:06:27.437 に答える
4

If these are non static field definitions you can not use the field initializers like that, you must put the data in the constructor.

class MyClass
{
    Dictionary<string, List<string>> myD;        
    List <string> MyList;

    public MyClass()
    {
        MyList = new List<string>() { "1" };
        myD = new Dictionary<string, List<string>>()
        {
          {"tab1", MyList }
        };
    }
}
于 2013-01-23T04:19:38.963 に答える