c# - 从静态函数访问外部变量

标签 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;
}

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

有办法吗?

我试过:

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/

相关文章:

c# - 无法将类型隐式转换为 'string' 错误

json - json字符串未解析

C#比较字符串中的字符

c++ - 静态初始化困惑

c++ - 静态构造函数顺序与组合是否正确

c# - 如何将 JSON 中的键值对更改为 XML 属性而不是节点

c# - 动态创建的按钮,但为它们创建的事件未触发

java - 为什么允许在接口(interface)中实现

c# - 阅读器关闭时读取的尝试无效。 C# 数据库

android - android xml文件中的硬编码字符串有什么问题?