C# automatic properties - is it possible to have custom getter with default setter?

后端 未结 5 1107
清酒与你
清酒与你 2021-01-04 13:44

It\'s possible I shouldn\'t even be attempting this in the first place, but here\'s what I have so far:

public List AuthorIDs
{
    get
    {
             


        
5条回答
  •  灰色年华
    2021-01-04 14:48

    if you want to do it your way, just do the following:

    private List authorIDs;
    public List AuthorIDs
    {
        get
        {
            var l = new List();
            using (var context = new GarbageEntities())
            {
                foreach (var author in context.Authors.Where(a => a.Books.Any(b => b.BookID == this.BookID)).ToList())
                {
                    l.Add(author.AuthorID);
                }
            }
            return l;
        }
    
        set{authorIDs = value; //this does not make much sense though ... what are you trying to do by setting authorIDs?
    }
    }
    

    but just like others are saying, this is an overkill for a property, put it in the method, something like

    public List GetAuthorIDs(int bookId)
        {
                var l = new List();
                using (var context = new GarbageEntities())
                {
                    foreach (var author in context.Authors.Where(a => a.Books.Any(b => b.BookID == bookId)).ToList())
                    {
                        l.Add(author.AuthorID);
                    }
                }
                return l;
            }
    

提交回复
热议问题