为自定义数据类型属性提供值

本文关键字:属性 定义数据类型 | 更新日期: 2023-09-27 18:30:08

我有MVC 5 中的模型

public class AppUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public PhoneNumbers CellNo { get; set; }
    public PhoneNumbers WorkNo { get; set; }
    public PhoneNumbers HomeNo { get; set; }
    public Address OfficeAddress { get; set; }
}

public class PhoneNumbers
{
    public string CountryCode { get; set; }
    public string AreaCode { get; set; }
    public string Number { get; set; }
}
public class Address
{
    public string address { get; set; }
    public string City { get; set; }
    public string ZipCode { get; set; }
    public string State { get; set; }
}

当我想像一样在模型AppUser中添加数据时

 AppUser.WorkNo.CountryCode= array[1];

它给出错误

 "An exception of type 'System.NullReferenceException' occurred in WebApp.dll but was not handled in user code
 Additional information: Object reference not set to an instance of an object."

我认为我做错了,请有人指导我解决这个错误?谢谢,

为自定义数据类型属性提供值

当您引用这个时:

AppUser.WorkNo.CountryCode

WorkNo属性为null。如果存在WorkNo的有效实例,则可以在该实例上引用CountryCode。但由于WorkNo是一个引用类型,除非实例化它,否则它默认为null

你可以在你的模型的构造函数中做什么:

public class AppUser
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public PhoneNumbers CellNo { get; set; }
    public PhoneNumbers WorkNo { get; set; }
    public PhoneNumbers HomeNo { get; set; }
    public Address OfficeAddress { get; set; }
    public AppUser()
    {
        CellNo = new PhoneNumbers();
        WorkNo = new PhoneNumbers();
        HomeNo = new PhoneNumbers();
        OfficeAddress = new Address();
    }
}

这样,维护对象有效状态的责任就封装在对象本身中,实例化其属性以供代码使用。