C#中的变量范围

Lou*_*Lou 2 c# variables scope

我的Web服务程序应该生成一个随机代码并将其返回给客户端程序.现在它返回""作为代码而不是随机生成的代码.我的变量范围有什么问题?谢谢.

public class Service1 : System.Web.Services.WebService
{
    private string code = "";

    [WebMethod]
    public void StartGame()
    {
        // Pick a secret code
        // R, B, G, O, T, W, P, Y
        Random random = new Random();
        for (int i = 0; i < 4; i++)
        {
            int num = random.Next(8) + 1;
            if (num == 1)
                this.code += "R";
            else if (num == 2)
                this.code += "B";
            else if (num == 3)
                this.code += "G";
            else if (num == 4)
                this.code += "O";
            else if (num == 5)
                this.code += "T";
            else if (num == 6)
                this.code += "W";
            else if (num == 7)
                code += "P";
            else if (num == 8)
                this.code += "Y";
        }
    }

    [WebMethod]
    public string MakeGuess(string guess)
    {
        return this.code;
    }
}
Run Code Online (Sandbox Code Playgroud)

Meh*_*ari 12

问题是这些方法是在类的两个单独实例上调用的.当一个HTTP请求进入时,每个方法在一个新的类实例上调用一次,该类将被丢弃.由于HTTP协议的无状态特性,服务器将不知道这些请求是否以某种方式相关.