繁体   English   中英

未将对象引用设置为对象的实例,null

[英]Object reference not set to an instance of an object, null

我不断收到此错误消息: 对象引用未设置为对象的实例。

  private static void GetIPInfo(User user)
  {
      string ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();

      string city = string.Empty;
      string region = string.Empty;
      string country = string.Empty;
      double? latitude = -1.00;
      double? longitude = -1.00;

      LocationTools.GetLocationFromIP(ipAddress, out city, out region, out country, out latitude, out longitude);

      user.IPAddress = user.IPAddress; **//error is pointing here**
  }

我需要实例化某些东西吗?

这样会解决问题吗?

 user.IPAddress new user.IPAddress = user.ipAddress;

您究竟希望该语句实现什么:

user.IPAddress = user.IPAddress;

我希望它充其量是没有行动的。 碰巧的是, user变量的值似乎为空。

目前尚不清楚该方法的目的,但大概是如果user为null,则该请求将未经身份验证。 GetXyz方法具有void返回类型很奇怪。 例如应该是PopulateIPInfo吗? 在那种情况下,传递一个null引用似乎是一个错误-但您确实需要确定该方法的用途... 在该方法内创建一个新的User实例不太可能会有用从长远来看。

怎么样:

user = new User; // Or whatever user is supposed to be

user.IPAddress = ipAddress; // Now you can assign an ip address to this property

这取决于您调用GetIPInfo(User user)的方式 看来您以user身份传递null。 也许你应该写一些像

GetIPInfo(new User());

但是尚不清楚是否必须以某种方式初始化User,或者是否足以创建一个空实例。 此外,我不了解您要使用user.IPAddress = user.IPAddress;做什么 除非在IPAddress的设置器中有其他代码引起某种附带影响,否则这条指令似乎根本没有任何作用,但这是我要避免的事情。

评论后编辑:

如果我做对了(但我不确定),也许这与您真正需要的东西更相似:

私人静态用户GetIPInfo(){用户user = new User();

  string ipAddress = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();

  string city = string.Empty;
  string region = string.Empty;
  string country = string.Empty;
  double? latitude = -1.00;
  double? longitude = -1.00;

  LocationTools.GetLocationFromIP(ipAddress, out city, out region, out country, out latitude, out longitude);

  user.IPAddress = ipAddress; 
  // other code to fill the other fields of User

  return user;
}

然后,您可以调用它并获得User的新实例,该实例可以分配给变量或根据需要使用。

正如乔恩指出的那样,您的user似乎为空。 我认为问题出在调用方法中,而不是在GetIPInfo 您可能想在方法中添加一些参数检查。 另外,我认为这种方法看起来很奇怪,但是我可能只是没有适当的上下文来理解它为何看起来如此。

System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]引发System.NullReferenceException“Object reference not set to an instance of an object.” -如果请求中未提供IP地址,则错误。 因此,您应该检查该语句是否引发异常。

暂无
暂无

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

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