创建构造函数并发送给视图
本文关键字:视图 并发 构造函数 创建 | 更新日期: 2023-09-27 18:08:09
我正在为我的狗创建一个谱系树,但我遇到了一些麻烦。我有三个类:
犬组:
public class Dog
{
public string Name { get; set; }
public string Merit1 { get; set; }
public string Merit2 { get; set; }
}
系谱类:
public class Pedigree
{
public Dog Father { get; set; }
public Dog GrandFather { get; set; }
public Dog GrandMother { get; set; }
public Dog GrandFathersFather { get; set; }
etc....
我想发送给视图的类,这里有硬编码的值,只是为了让我开始:
public class DogContentPage : ContentPage
{
public DogContentPage()
{
Name = "The Dog";
Age = "4";
Pedigree = new Pedigree();
{
mother = new Dog {Name = "Chanelle", Merit1 = "Universal"};
father = new Dog {Name = "dfdfdf", Merit1 = "dfdfdfdfdf"};
};
}
public string Name { get; set; }
public string Age { get; set; }
public Dog mother { get; set; }
public Dog father { get; set; }
}
在视图中,我尝试这样做:
@model EmmysBlog_Core.Models.Dog.DogContentPage
@{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>@Model.Name</h1>
<p>@Model.Pedigree.Mother.Name</p>
<p>@Model.Pedigree.Mother.Merit1</p>
我得到的错误是,对象没有设置为实例…我想要的是能够显示我的狗的属性…我错过了什么?
在Pedigree
构造函数中,您还需要实例化属性类,它们没有实例化,因此会抛出null引用异常:
public Pedigree()
{
this.Mother = new Dog{Name = "Chanelle", Merit1 = "Universal"};
this.Father = new Dog{Name = "dfdfdf", Merit1 = "dfdfdfdfdf"};
this.GrandFather = new Dog();
this.GrandMother = new Dog();
this.GrandFathersFather = new Dog();
}
在你的代码中也有错误,在你的方式中应该是这样的:
Pedigree obj = new Pedigree
{
Mother = new Dog {Name = "Chanelle", Merit1 = "Universal"};
Father = new Dog {Name = "dfdfdf", Merit1 = "dfdfdfdfdf"};
};