[英]Accessing a dictionary from methods outside main in C#
我正在创建一个字典,然后用main()中的条目填充它,然后调用一个使用所述字典的方法。 如果在传递给此方法的参数中包含字典,如何在不收到错误的情况下访问它?非静态字段,方法或属性'XXX.YYY.dict'需要对象引用?
编辑:这是代码请求:
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);
}
}
在FCheck中发生错误,以下行:
FCheck = dict(condensedBoard);
使其成为您的Program类的静态成员。 你没有显示任何代码,但听起来你有一个控制台应用程序,所以它会像这样工作:
class Program
{
static Dictionary<string, string> _myDict;
static void Main(string[] args)
{
// Fill it here
}
void MyFunc()
{
// Access it here
}
}
您可以将字典设置为主要简单填充的静态变量,但将变量传递给需要它们的类会更好
让它全球化?
static Dictionary<X, X> Entries;
public static void main(string[] args)
{
// populate and then call dostuff
}
public static X dostuff(a)
{
return Entries[a];
}
?
您可以将字典设置为类中的静态字段。 但是应该谨慎使用静态字段,因此将其作为参数传递可能是更好的解决方案。 特别是如果您的应用程序随着时间的推移而变大。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.