gpt4 book ai didi

c# - 从 Web 服务实例化对象与从常规类实例化对象

转载 作者:太空狗 更新时间:2023-10-29 21:41:20 25 4
gpt4 key购买 nike

我有一个非常基本的网络服务:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace WebService1
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{

public int myInt = 0;

[WebMethod]
public int increaseCounter()
{
myInt++;
return myInt;
}

[WebMethod]
public string HelloWorld()
{
return "Hello World";
}

}
}

当我运行该项目时,我的浏览器打开并向我显示该服务: enter image description here


在不同的解决方案上:(控制台应用程序)

我可以通过添加引用来连接到该服务:

enter image description here

enter image description here

然后点击添加网络引用按钮: enter image description here

最后,我输入刚刚创建的服务的 url: enter image description here

现在我可以从我的控制台应用程序中实例化一个类 Service1 的对象:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication36
{
class Program
{
static void Main(string[] args)
{
localhost.Service1 service = new localhost.Service1();

// here is the part I don't understand..
// from a regular class you will expect myInt to increase every time you call
// the increseCounter method. Even if I call it twice I always get the same result.

int i;
i=service.increaseCounter();
i=service.increaseCounter();


Console.WriteLine(service.increaseCounter().ToString());
Console.Read();


}
}
}

为什么我每次调用 increaseCounter 方法时 myInt 都不增加?每次我调用该方法时,它都会返回 1。

最佳答案

通过旧的 .asmx 技术创建的服务不是单例实例。这意味着每次调用服务器都会实例化一个新的服务实例。两个真正的解决方案,要么使用静态变量(呃....),要么改用 WCF。

关于c# - 从 Web 服务实例化对象与从常规类实例化对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7589301/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com