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

冷暖自知 提交于 2019-12-12 14:28:00

问题


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.

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


回答1:


  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.



回答2:


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()
        }
}


来源:https://stackoverflow.com/questions/16067642/extensions-method-trying-to-call-protected-methods-wrong-exhibition-of-dynamic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!