C# returning Exception at runtime
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;
} }
精彩评论