简体   繁体   中英

Confused about inheritance in c#

I have a base class looking like this:

public class BaseController : Controller {
}

Classes that inherit this:

public class ABC : BaseController {
   public void Create(string a, string b) {
      var Meta = new Meta();
      Meta.Title = "test";
   }
}

public class DEF : BaseController {
   public void Create(string a, string b, string c) {
      var Meta = new Meta();
      Meta.Title = "job";
   }
}

Every one of the classes that inherits from BaseController needs to create an instance of Meta();

Is there some way that I could move this creation from the classes ABC & DEF into the base controller? Note that some of the methods in classes ABC, DEF etc have different number of arguments.

One idea I had for this was to do the following in the BaseController:

    public Meta Meta { get; set; }
    protected override void Initialize(RequestContext requestContext)
    {
        if (Meta == null) { Meta = new Meta(); }
    }

Is this a valid thing to do. Also if I did this in the BaseController then would the field Meta be available in classes that inherit from the BaseController?

I'd probably do it like below. And yes, you can access meta if you define it protected (or public of course).

public class BaseController : Controller { 
   protected Meta meta;

   public void Create() { 
      meta = new Meta(); 
   } 
}

public class ABC : BaseController { 
   public void Create(string a, string b) { 
      base.Create();
   } 
} 

public class DEF : BaseController { 
   public void Create(string a, string b, string c) { 
      base.Create();
   } 
} 

I would do something like this:

public class BaseController : Controller {
    protected Meta Meta { get; set; }
    protected void Create()
    {
        if (Meta == null) { Meta = new Meta(); }
    }
}

public class ABC : BaseController {
   public void Create(string a, string b) {
      base.Create();
   }
}

public class DEF : BaseController {
   public void Create(string a, string b, string c) {
      base.Create();
   }
}

If you only want access to Meta from the base class then make meta private . If you want access to Meta only from things that inherit from the base class then you make it protected . If you want anything that creates an instance of ABC or DEF to have access to Meta too then make it public .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM