C# 类空引用
我正在使用 Ajax 从服务器取回值,但是当调用方法 incrementvalue()
时,_value
具有空引用,即使它是之前在intialisevalue()
方法。我下面有一些示例代码。
public class test
{
public int value;
public void increment(int _value)
{
value = value + _value;
}
public void setvalue(int _value)
{
value = _value;
}
}
public test _value;
public JsonResult intialisevalue()
{
_value = new test();
_value.setvalue(9);
return Json(_value);
}
public JsonResult incrementvalue()
{
_value.increment(2);
return Json(_value);
}
有什么想法吗?
I'm using Ajax to bring back values from the server, but when calling the method incrementvalue()
, _value
has a null reference even though it is set up previously in the intialisevalue()
method. I have some example code below.
public class test
{
public int value;
public void increment(int _value)
{
value = value + _value;
}
public void setvalue(int _value)
{
value = _value;
}
}
public test _value;
public JsonResult intialisevalue()
{
_value = new test();
_value.setvalue(9);
return Json(_value);
}
public JsonResult incrementvalue()
{
_value.increment(2);
return Json(_value);
}
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
控制器仅存在于请求中。发送响应后,控制器被处理。因此,
test
不再存在。您需要将测试对象传递到控制器中controllers only exist within the request. after the response is sent the controller is disposed. thus,
test
no longer exists. you need to pass the test object into the controller在调用控制器之间不会保留您的值。当您调用incrementvalue 方法时,它会使用该字段的新副本。您可能会发现它抛出异常,因为 _value 为 null。
当您调用控制器时,您应该将值的副本传递到incrementvalue方法中,然后递增该方法并再次返回它。
Your value is not retained between calls to the controller. When you call the incrementvalue method, it's working with a new copy of that field. You'll probably find that it's throwing an exception because _value is null.
You should pass the copy of value into the incrementvalue method when you call the controller, then increment that and return it again.
您不会在以下方法中为
_value
分配新引用。您应该按如下方式修改它。
You're not assigning a new reference to
_value
in the following method.you should modify it as follows.
您需要在每次调用服务器时重新初始化 _value 。 HTTP 是无状态的,您的变量不会在请求之间保留其状态。
You need yo re-initialize _value each call to the server. HTTP is stateless, your variables do not keep their state between requests.