将类对象作为属性的类

本文关键字:属性 对象 | 更新日期: 2023-09-27 18:09:58

我有一个属性类PropUser:

public class PropUser
{
    public int UserId { get; set; }
    public int ParentId { get; set; }
    public PropProduct Product { get; set; }
}

这里第三个属性Product是PropProduct的对象PropProduct是另一个属性类

 public class PropProduct
{
    public int ProductId { get; set; }
    public string  Name { get; set; }
    public int Price { get; set; }
}
现在,在下面的代码中:
PropUser user = new PropUser();
    user.Product.Name = "Reebok";

user.Product抛出"Object reference not set to a instance of a Object "异常。

我知道user.Product是空的,那么如何初始化它以便我可以设置user.Product.Name="Reebok"

将类对象作为属性的类

如果您希望在类创建时立即初始化它,请创建一个构造函数并在那里初始化它:

public class PropUser
{
    public PropUser
    {
        Product = new PropProduct();
    }
    public int UserId { get; set; }
    public int ParentId { get; set; }
    public PropProduct Product { get; set; }
}

如果您想在创建新的PropUser时初始化Product,只需在PropUser类中添加一个初始化它的构造函数。

public class PropUser
{ 
    //Your Properties
    public PropUser() 
    {
        Product = new PropProduct();
    }
}

如果你想"按需"做,所以有时可以是null,在分配字符串之前或同时创建一个新的PropProduct对象:

PropUser user = new PropUser();
user.Product = new PropProduct {Name = "Reebok"};

您需要使用new运算符初始化PropProduct对象,然后赋值。

试试这个:

PropUser user = new PropUser();
user.Product = new PropProduct();
user.Product.Name = "Reebok";

相关文章: