开发者

Accessing a dictionary from methods outside main in C#

I am creating a dictionary and then populating it with entries in main(), then calling a method which uses said dictionary.开发者_StackOverflow Short of including the dictionary in the arguments being passed to this method, how can I access it without getting the error 'An object reference is required for the non-static field, method or property 'XXX.YYY.dict'?

Edit: Here is code requested:

public static void Main()

    {
        ulong board = AS | KH | FD | FC | TH | SH | NC;
        Dictionary<ulong, int> dict; dict = new Dictionary<ulong, int>();

        for (int a = 0; a < 49344; a++)
        {
            dict.Add(helloworld.Table.handhashes[a], helloworld.Table.ratings[a]);
        }


        int hand = 0;

        for (int ai1 = 0; ai1 < 100000000; ai1++)
        {
            hand = FCheck(board);
        }
}

Error happening in FCheck, following line:

FCheck = dict(condensedBoard);


Make it a static member of your Program class. You didn't show any code but it sounds like you have a console app, so it would work something like this:

class Program
{
   static Dictionary<string, string> _myDict;

   static void Main(string[] args)
   {
       // Fill it here
   }

   void MyFunc()
   {
      // Access it here
   }
 }


You could make the dictionary a static variable that main simply populates but it's far nicer to pass variables through to classes that need them


Make it global?

static Dictionary<X, X> Entries;

public static void main(string[] args)
{ 
    // populate and then call dostuff 
}

public static X dostuff(a) 
{
    return Entries[a];
}

?


You can make your dictionary a static field on the class. But static fields should be used with caution, so passing it as a parameter is probably a better solution. Especially if your application is going to get bigger with time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜