有人可以帮助我解决我班上的问题吗?
我有一个地址类:
public class Address
{
public string addressDescription { get; set; }
public string addressNumber { get; set; }
public string adddressLine1 { get; set; }
public string adddressLine2 { get; set; }
public string adddressLine3 { get; set; }
public string addressPostCode { get; set; }
public double addressLatitude { get; set; }
public double addressLongitude { get; set; }
}
我有一个路线类:
public class Route
{
public Address from { get; set; }
public Address to { get; set; }
}
在我的控制器中,我设置了一些这样的虚拟信息:
public ActionResult FareCalculator(string from , string to)
{
var myroute = new Route();
myroute.from.addressDescription = from;
myroute.from.addressLatitude = 51.481581;
myroute.from.addressLongitude = -3.179090;
myroute.to.addressDescription = to;
myroute.to.addressLatitude = 51.507335;
myroute.to.addressLongitude = -0.127683;
return View(myroute);
}
但是当我运行项目时,它会落在myroute.from.addressDescription = from;表示对象引用未设置为对象的实例。
我看不出我做错了什么。有人可以帮忙吗?
由于
崔佛
答案 0 :(得分:3)
您需要创建Address
的新实例,并将其分配给from
和to
:
public ActionResult FareCalculator(string from , string to)
{
var myroute = new Route();
myroute.from = new Address(); // new instance
myroute.from.addressDescription = from;
myroute.from.addressLatitude = 51.481581;
myroute.from.addressLongitude = -3.179090;
myroute.to = new Address(); // new instance
myroute.to.addressDescription = to;
myroute.to.addressLatitude = 51.507335;
myroute.to.addressLongitude = -0.127683;
return View(myroute);
}
答案 1 :(得分:2)
我可以建议使用构造函数初始化from和to字段吗?否则,每次使用Route类时都必须新建对象。
public class Route
{
public Address from { get; set; }
public Address to { get; set; }
public Route()
{
from = new Address();
to = new Address();
}
}
这样您就可以使用您提供的代码:
var myroute = new Route();
myroute.from.addressDescription = from;
myroute.from.addressLatitude = 51.481581;
myroute.from.addressLongitude = -3.179090;
myroute.to.addressDescription = to;
myroute.to.addressLatitude = 51.507335;
myroute.to.addressLongitude = -0.127683;
return View(myroute);
答案 2 :(得分:1)
您已创建Route
个实例,但忘记创建Address
的新实例(from
和to
):
var myroute = new Route
{
from = new Address(),
to = new Address()
};
答案 3 :(得分:0)
myroute.from
和myroute.to
应该是Address
类的实例。
public ActionResult FareCalculator(string from , string to)
{
var myroute = new Route();
myroute.from = new Address();
myroute.from.addressDescription = from;
myroute.from.addressLatitude = 51.481581;
myroute.from.addressLongitude = -3.179090;
myroute.to = new Address();
myroute.to.addressDescription = to;
myroute.to.addressLatitude = 51.507335;
myroute.to.addressLongitude = -0.127683;
return View(myroute);
}