0

我正在使用延迟加载来加载有关票证消息所属的支持票证的信息。TicketMessage 是 Ticket 的子级。在我的 TicketMessage 类中,当引用 TicketMessage 对象的 Ticket 属性时,我有以下代码来延迟加载 Ticket 对象:

// Lazy loading of Ticket object
private Ticket _Ticket { get; set; }
public Ticket Ticket
{
    get
    {
        return this._Ticket ?? (this._Ticket = new Ticket(TicketID, ClientID, ConnectionString, Person.PersonID));
    }
}

但是,我遇到的行为表明每次实例化 TicketMessage 类时都会出现此对象,从而导致一些不需要的空引用异常。我的延迟加载模式有什么明显的错误吗?

4

3 回答 3

1

Don't make _Ticket as a property. Try this:

private Ticket _Ticket = null;

public Ticket Ticket
{
    get
    {
        return this._Ticket != null ? this._Ticket : (this._Ticket = new Ticket(TicketID, ClientID, ConnectionString, Person.PersonID));
    }
}
于 2013-01-21T10:21:32.570 回答
1

I would say your NRE problem is more likely to be Person being null rather than an issue with the null-coalescing operation.

That being said, I don't particularly like the idea of doing an assignment in that way. From a readability point of view it would be much clearer written as:

private Ticket _ticket;
...
public Ticket Ticket
{
    get
    {
        if (this._ticket == null)
        {
            this._ticket = new Ticket(TicketID, ClientID, ConnectionString, Person.PersonID);
        }
        return this._ticket;
    }
}
于 2013-01-21T10:25:51.410 回答
1

Person.PersonID 调用中的问题,您应该确保该对象已初始化。

.Net 4 有一个完美的类 Lazy<>

private Lazy<Ticket> ticket = new Lazy<Ticket>(() => new Ticket(TicketID, ClientID, ConnectionString, Person.PersonID));

public Ticket Ticket
{
    get { return ticket.Value; }
}
于 2013-01-21T11:19:26.563 回答