开发者

C# returning Exception at runtime

开发者 https://www.devze.com 2023-01-05 22:45 出处:网络
Don\'t think this is possible but thought I would ask and maybe someone could suggest an alternative technique or pattern.

Don't think this is possible but thought I would ask and maybe someone could suggest an alternative technique or pattern.

Say I have a Customer class that has as list of Books which are both pulled seperately from an external source. If the Customer class is successfull but the Books failed to load I don't want to throw an Exception unless the client tries to access the Books property so..

this.Books = new List<Book>()
{
    throw new Exception("Books couldn't load because blah blah");
};

Is开发者_运维问答 something along these lines possible?


How about placing this logic into a Books property backed off with a private field books:

public IEnumerable<Book> Books //or public IList<Book> Books
{
    get
    {
        if(this.books == null)
            throw new Exception("Books couldn't load because blah blah");
        return this.books;
    }
}


In your Books property, add a logic to check whether the collection is loaded:

public List<Book> Books { get {
  if (this.books == null) // or any other flag check
    throw new InvalidOperationException("Books are not loaded.");
  return this.books;
} }
0

精彩评论

暂无评论...
验证码 换一张
取 消