简体   繁体   中英

How can I adapt a c# class with private methods?

I would like to adapt a class with a private method, so that the adapter calls this private method:

Consider this class

public class Foo
{
   private void bar()
}

I would like a class that follows the command pattern, and calls bar() in it's execute method:

public class FooCommand
{
   private Foo foo_;
   public FooCommand(Foo foo)
   {
      foo_ = foo;
   }
   public void execute()
   {
      foo.bar();
   }
}

Any ideas would be greatly appreciated.

Thanks!

I believe there are many options:

  • Instead of a FooCommand , use an interface ICommand with an Execute method. Then declare Foo in such a way that it implements ICommand :

     public class Foo : ICommand { private void bar() { ... } void ICommand.Execute() { bar(); } } 

    I believe this is the most attractive solution: the method can still be private; you don't need to instantiate an extra FooCommand for every Foo ; and you don't need to declare a separate XCommand class for every X class that wants it.

  • Declare the FooCommand class inside the Foo class so that it becomes a nested class . Then the FooCommand can access the private method.

  • Declare the bar method public or internal .

  • Declare the bar method protected or protected internal and then derive FooCommand from Foo .

  • Use Reflection to invoke the private method (use Type.GetMethod followed by MethodBase.Invoke ). I believe most developers would consider this a dirty hack.

You would need to at least make bar() protected rather than private. Private functions can only be called by the class that declares them, unless you decide to use Reflection which then places security requirements on your application.

The only way to do this would be to use reflection and invoke the method that way, however I would strongly suggest against doing that. Why not just make the method internal?

   public void execute()
   {
       var m = foo_.GetType().GetMethod("bar", BindingFlags.NonPublic|BindingFlags.Instance);
       m.Invoke(foo_, null);

   }

I agree with the other posters who say make the method internal and use InternalsVisibleToAttribute if needed.

Do you have access to class Foo as in access to modify the class? If not, I don't believe you can call its private method bar() from another class.

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