从静态函数访问外部变量

Lor*_*ich 2 c# string static void output

我有一个静态功能:

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;
}
Run Code Online (Sandbox Code Playgroud)

但每次我调用函数时,列表都会重置,所以我想从静态函数外部访问列表.

有办法吗?

我试过了:

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;
}
Run Code Online (Sandbox Code Playgroud)

但后来我得到一个索引超出范围错误(不知道为什么).

有人可以帮忙吗?

Tim*_*ter 9

您需要将其作为静态字段变量添加到类中:

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;
}
Run Code Online (Sandbox Code Playgroud)