我有一个静态函数:
static string GenRan()
{
List<string> s = new List<string> {"a", "b"};
int r = Rand();
string a = null;
if (r == 1)
{
a += s[0];
s.RemoveAt(0);
}
if (r == 2)
{
a += s[1];
s.RemoveAt(1);
}
return a;
}
当然,每次我调用函数时,列表都会被重置,所以我想从静态函数外部访问列表。
有办法吗?
我试过:
static void Main(string[] args)
{
List<string> s = new List<string> {"a", "b"};
string out = GenRan(s);
}
static string GenRan(List<string> dict)
{
int r = Rand();
string a = null;
if (r == 1)
{
a += s[0];
s.RemoveAt(0);
}
if (r == 2)
{
a += s[1];
s.RemoveAt(1);
}
return a;
}
但随后我得到一个索引超出范围的错误(不知道为什么)。
有人能帮忙吗?
最佳答案
您需要将其作为static field 添加到类中变量:
private static List<string> s = new List<string> { "a", "b" };
static string GenRan()
{
int r = Rand();
string a = null;
if (r == 1)
{
a += s[0];
s.RemoveAt(0);
}
if (r == 2)
{
a += s[1];
s.RemoveAt(1);
}
return a;
}
关于c# - 从静态函数访问外部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13663844/