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

后端 未结 5 1074
清酒与你
清酒与你 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:29

    This answer goes a bit wider than simply getting rid of the setter on the property - combine it with the rest of the answers and comments, and take the bits that make sense. Hopefully the bit at the end will help too, maybe just not right now.

    If you're using this in a model for data binding purposes and thus want it exposed as a property, I would do something like this:

    public class BookModel
    {
        public IList AuthorIds { get; set; }
    }
    

    Make a service which you will call to populate your model:

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

    In your controller:

    public ViewResult List(int id)
    {
        var model = new BookModel 
        {
            AuthorIds = service.GetAuthorIDs(id)
        };
    
        return View(model);
    }
    

    I explicitly haven't included how to instantiate the book service in the controller. My preference would be to inject it at runtime in a constructor, but this will require you to have a custom controller factory - one step at a time. You could just new it up in the default constructor:

    private readonly BookService service; 
    
    public BookController()
    {
        service = new BookService();
    }
    

    In an ideal world though, I would do this:

    private readonly BookService service; 
    
    public BookController(BookService service)
    {
        if(service == null)
            throw new ArgumentException("service must be supplied");
    
        this.service = service;
    }
    

    However the default MVC controller factory expects controllers to have a default parameter, so doing it with constructor injection will take a bit more work.

提交回复
热议问题