繁体   English   中英

C#中的变量范围

[英]Variable Scope in C#

我的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;
    }
}

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

你有两个不同的电话,一个用于调用开始游戏,另一个用于调用MakeGuess? 单独的调用意味着在服务器端创建不同的对象。 您应该创建会话或使代码变为静态。

提交时不另外评论:

public static string GenerateRandomCode(int length)
{
    const string charset = "RBGOTWPY";

    string randomCode = "";
    Random random = new Random();

    while (length > 0)
    {
        length--;
        randomCode += charset[random.Next(charset.Length)];
    }
    return randomCode;
}

如果没有特别需要两个电话,为什么不制作一个简单的方法呢?

`

[WebMethod]
    public string MakeGuess(string guess)
    {
        private string code = "";
        // 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";
        }
        return code;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM