Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)

As a test for the forum and also because I don't know a good solution.

I've got a low down base class with a protected method that is overridden on implimentations, something like:

class Foo 
{
  protected Bar()
  {
    // base work
  }
}

class Tang : Foo
 {
  protected override Bar()
  {
    // my bits
    base.Bar();
  }
}

Now I want to have a wrapper class that can take ANY derived Foo (say a Tang) and do its wrapper work then call out to the wrapped Foo.

Class Outside : Foo
{
  private Foo wrapped;

  Outside (Foo wrapped)
      : base()
  {
    this.wrapped = wrapped;
  }

  protected override Bar()
  {
    // my bits
    // then call the wrapped one:
    this.wrapped.Bar();
  }
}
Now because Bar is protected and Outside is in a different namespace to Foo so I can't call wrapped. Any idea of a what or how [-700 for suggesting any change to Foo, it is off limits]

[Additional Information]

I'm still fiddling, we did a nasty to get things working but it wasn't ideal; this was based on the WrappedFoo solution.

The big problem is that Foo's namespace is off-limits, it's in the core infrastructure, and we need a solution in the Tang namespace.

Posted
Updated 22-Nov-09 22:13pm
v7

This isn't my strong point, but perhaps you could cast wrapped before calling Bar? If that doesn't work, then you could use Reflection, in some method like this:

C#
Type tp = this.wrapped.GetType();
Type baseType = tp.BaseType;
MethodInfo baseMethod = baseType.GetMethod("Bar", BindingFlags.DeclaredOnly | BindingFlags.IgnoreCase);

baseMethod.Invoke(this.wrapped, arguments); 

If DeclaredOnly doesn't work, then you could try FlattenHierarchy. I haven't tested that, but it might work

I updated your post to fix a spelling error in the title by the way.

 
Share this answer
 
v2

 How about a wrappable foo class:

C#
class WrappableFoo : Foo
{  
      public void CallBar()
      { 
             base.Bar(); 
      } 
} 

Tang must then inherit WrappableFoo

C#
class Tang : WrappableFoo
 {
  protected override Bar()
  {
    // my bits
    base.Bar();
  }
}  

And Outside must always take a WrappableFoo

 

C#
Class Outside : Foo
{
  private WrappableFoo wrapped;

  Outside (WrappableFoo wrapped)
      : base()
  {
    this.wrapped = wrapped;
  }

  protected override Bar()
  {
    // my bits
    // then call the wrapped one:
    this.wrapped.CallBar();
  }
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900