I have a project which uses Autofac to instantiate the objects
builder.RegisterType<AbcWebWorkContext>().As<IWorkContext>().InstancePerHttpRequest();
This AbcWebWorkContext
is a subclass of WebWorkContext
:
public partial class AbcWebWorkContext : WebWorkContext
In my AbcWebWorkContext
I would like to hide a method and a property from the parent class
protected new Customer GetCurrentCustomer(){ //do stuff }
new public Customer CurrentCustomer { //do studd }
But when someone calls
_workContext.CurrentCustomer
The base class property is called. If I call it like this
((AbcWebWorkContext) _workContext).CurrentCustomer
it works.
I would like to know why I am not able to hide the parent method. I can't change the called class because it is in NopCommerce
's core, which I would not like to change.
Why is it not hiding the method?
Base class declaration of the methods:
protected Customer GetCurrentCustomer() { // do stuff }
public Customer CurrentCustomer{ // do stuff }
calling GetType()
on _workcontext
will output
{Name = "AbcWebWorkContext" FullName = "Nop.Web.Framework.AbcWebWorkContext"}
The type hierarchy is IWorkContext
(interface) « WebWorkContext
« AbcWebWorkContext
_workContext
is declared as IWorkContext
and Autofac generates an instance as AbcWebWorkContext
(as shown above)
The new
keyword means that the subclass's method hides the baseclass's CurrentCustomer
instead of overriding, so WebWorkContext.CurrentCustomer
is a completely different method than AbcWebWorkContext.CurrentCustomer
.
You must declare the base class's method as
virtual Customer CurrentCustomer { ... }
And the subclass's method
override Customer CurrentCustomer { ... }
I suggest you read more about polymorphism in c# .
If the methods you're using are actually defined in an interface, IWebWorkContext
, you simply encapsulate the base class rather than inheriting from it, like this:
class AbcWebWorkContext : IWebWorkContext
{
private WebWorkerContext _inner = new WebWorkerContext();
public Customer CurrentCustomer { ... }
}
If you can't make the base class's method virtual, you have to do something much less elegant, like reflection:
var prop = _workContext.GetType().GetProperty("CurrentCustomer");
var value = (Customer)prop.GetValue(_workContext, new object[0]);
I'm not sure if I got your questions right, but I think you need to add a virtual
modifier to the method in base class and add a override
modifier to method in the subclass.
Find out more on MSDN
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.