Basic problem (pseudocode):
interface ISomethingDoer
{
void DoSomething();
}
class A: ISomethingDoer
{
void ISomethingDoer.DoSomething()
{
Something.Do();
}
}
class B: A, ISomethingDoer
{
void ISomethingDoer.DoSomething()
{
if (reason)
{
base.DoSomething(); //this does not compile
}
SomethingElse.Do();
}
}
Is there any way to make this work without removing the explicit implementation from class A?
I would suggest changing your base class a little such that DoSomething calls a protected method:
class A: ISomethingDoer
{
void ISomethingDoer.DoSomething()
{
DoSomethingImpl();
}
protected void DoSomethingImpl()
{
Something.Do();
}
}
And then in B you can call DoSomethingImpl:
class B: A, ISomethingDoer
{
void ISomethingDoer.DoSomething()
{
if (reason)
{
DoSomethingImpl(); //this does compile
}
SomethingElse.Do();
}
}
The alternative method suggested by Lasse V. Karlsen is to use reflection:
class B: A, ISomethingDoer
{
void ISomethingDoer.DoSomething()
{
if (reason)
{
string baseName = $"{typeof(ISomethingDoer).FullName}.{nameof(DoSomething)}";
MethodInfo baseMethod = this.GetType().BaseType
.GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
.FirstOrDefault(m => m.IsPrivate && m.IsFinal && m.Name == baseName);
baseMethod.Invoke(this, new object[0]);
}
SomethingElse.Do();
}
}
But I don't like this approach since it uses reflection and is going to be slower. I used this answer to help me build the reflection solution.
You can use GetParameters() if you need to filter different overloads of the method, and you can specify arguments by building an object[] array containing them in the same positional order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With