Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extensions Method trying to call protected methods / wrong exhibition of dynamic parameters

I have a class named NIFERepository. It contains a SaveObject method, which returns nothing and performs an operation on a database.

public class NIFERepository<E>
{
    protected void SaveObject(object saveObject)
    {
        if (saveObject is E)
            this.RepositorySession.Merge(saveObject);
    }
}

1 . I wish to create a public extension method who calls this SaveObject() method, like this:

    public static class NIFERepositoryExtensions
    {
        public static T Save<T, E>(this T self, E saveObject) where T : NIFERepository<E>
        {
            self.SaveObject(saveObject);
            return self;
        }
    } 

But the protected scope doesn't allow my extensions method to recognize it.

Is there a way for me to get a method of this form to work?

2 . I created my extension method with 2 types: T and E. T is the instance who called it, and E is the defined type into my ProductRepository<Product>, for example. When I call this method, the defined type is not shown. enter image description here

Is there a way for me to get this to work?

like image 647
Kiwanax Avatar asked Mar 24 '23 07:03

Kiwanax


2 Answers

  1. You cannot use extension methods to violate encapsulation.
    If the class does not expose the method, you can't call it (except with Reflection).
    The method is (hopefully) protected for a reason; you're probably doing something wrong.
like image 152
SLaks Avatar answered Apr 13 '23 00:04

SLaks


Protected method are visible inside inherited classes. So do inheritance and create a public method that calls the base protected method like

public class BaseClass
{
  protected void SomeMethod()
   {

   }
}

public class ChildClass:BaseClass
{
  public void SomeMethodPublic()
        {
          base.SomeMethod()
        }
}
like image 37
Dan Hunex Avatar answered Apr 12 '23 23:04

Dan Hunex